package com.dhecp.project.api.service.impl;
import java.io.*;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bo.sellingpartnerapi.Feeds20210630.model.*;
import com.dhecp.common.config.Global;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.common.utils.log.BeanLogUtils;
import com.dhecp.core.utils.FroestHttPUtils;
import com.dhecp.core.utils.RedisUtil;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.api.api.FbaInboundApi;
import com.dhecp.project.api.api.FeedsApi;
import com.dhecp.project.api.client.ApiException;
import com.dhecp.project.api.client.model.SellerSecretsVO;
import com.dhecp.project.api.domain.*;
import com.dhecp.project.api.domain.Address;
import com.dhecp.project.api.enums.*;
import com.dhecp.project.api.mapper.*;
import com.dhecp.project.api.service.ApiFbaInboundService;
import com.dhecp.project.api.service.ApiLogService;
import com.dhecp.project.api.service.FbaBoxDetailService;
import com.dhecp.project.api.service.ProductBasisService;
import com.dhecp.project.api.util.ApiConfig;
import com.dhecp.project.api.util.Helper;
import com.dhecp.project.storage.domain.HwStorage;
import com.dhecp.project.storage.domain.HwTailprogramApi;
import com.dhecp.project.storage.domain.HwTailprogramdetail;
import com.dhecp.project.storage.mapper.HwStorageMapper;
import com.dhecp.project.storage.mapper.HwTailprogramMapper;
import com.dhecp.project.storage.mapper.HwTailprogramdetailMapper;
import com.squareup.okhttp.*;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName ApiFbaInboundServiceImpl
 * @Description 头程api
 * @Author fxz
 * @Date 2022-08-25 17:00
 */
@Service
public class ApiFbaInboundServiceImpl implements ApiFbaInboundService {

    private static final Logger logger = LoggerFactory.getLogger(ApiFbaInboundServiceImpl.class);

    @Autowired
    private ApiLogService apiLogService;

    @Autowired
    private AmazonShopMapper amazonShopMapper;

    @Autowired
    private FbaPlanOrderDetailMapper fbaPlanOrderDetailMapper;

    @Autowired
    private ModuleNidAndBidMapper moduleNidAndBidMapper;

    @Autowired
    private FbaShipmentMapper fbaShipmentMapper;

    @Autowired
    private FbaShipmentDetailMapper fbaShipmentDetailMapper;

    @Autowired
    private FbaPlanOrderMapper fbaPlanOrderMapper;

    @Autowired
    private FbaBoxDetailService fbaBoxDetailService;

    @Autowired
    private FbaBoxMapper fbaBoxMapper;

    @Autowired
    private FbaBoxDetailMapper fbaBoxDetailMapper;

    @Autowired
    private FbaDevanningMapper fbaDevanningMapper;

    @Autowired
    private FbaDevanningDetailMapper fbaDevanningDetailMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private AccountCountForCompanyMapper accountCountForCompanyMapper;

    @Autowired
    private StockControlMapper storageMapper;

    @Autowired
    private UpdateLogMapper updateLogMapper;

    @Autowired
    private SysAccountBandDeptMapper sysAccountBandDeptMapper;

    @Autowired
    private AccountDetailedForCompanyMapper businessMapper;

    @Autowired
    private LogsticsPatternMapper logsticsPatternMapper;

    @Autowired
    private LogsticsMmodeCkMapper logsticsMmodeCkMapper;

    @Autowired
    private StockControlRunningMapper stockControlRunningMapper;


    @Autowired
    private LogsticsMmodeMapper logsticsMmodeMapper;

    @Autowired
    private LogsticsMmodeGradsMapper logsticsMmodeGradsMapper;

    @Autowired
    private LogsticsMmodeDetailsMapper logsticsMmodeDetailsMapper;

    @Autowired
    private FbaSpellTickMapper fbaSpellTickMapper;

    @Autowired
    private FbaSpellTicketDetailMapper fbaSpellTicketDetailMapper;

    @Autowired
    private FbaLogsticsOrderDetailMapper fbaLogsticsOrderDetailMapper;

    @Autowired
    private GaugeMaintenanceMapper gaugeMaintenanceMapper;

    @Autowired
    private FbaCancelMapper fbaCancelMapper;

    @Autowired
    private HwTailprogramMapper hwTailprogramMapper;

    @Autowired
    private HwTailprogramdetailMapper hwTailprogramdetailMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysDepotInfoMapper sysDepotInfoMapper;

    @Autowired
    private AmazonAddressMapper amazonAddressMapper;

    @Autowired
    private TsChannelcodeMapper tsChannelcodeMapper;

    @Autowired
    private FbaWarehousingMapper fbaWarehousingMapper;

    @Autowired
    private FbaWarehousingDetailMapper fbaWarehousingDetailMapper;

    @Autowired
    private ProductBasisService productBasisService;

    @Autowired
    private HwStorageMapper hwStorageMapper;

    @Autowired
    private AmazonShopProductMapper amazonShopProductMapper;


    /**
     * 头程下单(手动创建货件)
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse addParcel(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<FbaPlanOrderDetail> fbaPlanOrderDetailList;
        Map<String, Object> params1;
        List<FbaPlanOrder> list = null;
        Address harvestAddress;
        UserInfo userInfo;
        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaPlanOrder.class);

            //箱规维护
            List<GaugeMaintenance> gaugeMaintenanceList = gaugeMaintenanceMapper.select();

            for (FbaPlanOrder fbaPlanOrder : list) {
                FbaPlanOrder fbaPlanOrder1 = fbaPlanOrderMapper.queryFirstByGuid(fbaPlanOrder.getGuid());
                if (fbaPlanOrder1 == null){
                    apiResponse.setMsg(fbaPlanOrder.getCode() + "头程计划不存在,请刷新后再次操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                if (fbaPlanOrder1.getState().equals("1")){
                    apiResponse.setMsg(fbaPlanOrder.getCode() + "头程计划已审核,请刷新后再次操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                userInfo = userInfoMapper.findByUserId(fbaPlanOrder1.getaUser());
                if ("自动".equals(fbaPlanOrder1.getCreationMethod())) {
                    apiResponse.setMsg(fbaPlanOrder.getCode() + "头程计划数据已更变,请刷新后再次操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                } else {
                    //手动创建 不执行后台api
                    FbaShipment fbaShipment = new FbaShipment();
                    harvestAddress = new Address();
                    InboundShipmentPlan inboundShipmentPlan = new InboundShipmentPlan();
                    //创建货件信息
                    addShipment(fbaPlanOrder1,harvestAddress,inboundShipmentPlan,fbaShipment,userInfo,apiResponse);
                    if (apiResponse.getCode() == 400){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

                    //查询头程计划详情信息
                    params1 = new HashMap<String, Object>();
                    params1.put("code", fbaPlanOrder1.getCode());
                    fbaPlanOrderDetailList = fbaPlanOrderDetailMapper.queryList(params1);
                    if (fbaPlanOrderDetailList.size() != 0) {
                        for (FbaPlanOrderDetail fbaPlanOrderDetail : fbaPlanOrderDetailList) {
                            //新增货件详情
                            addShipmentDetail(fbaPlanOrderDetail,fbaShipment,userInfo,apiResponse);
                            if (apiResponse.getCode() == 400){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }
                        }
                    }

                    FbaBox fbaBox = new FbaBox();
                    //创建装箱信息
                    addFbaBox(fbaShipment,fbaBox,userInfo,apiResponse);
                    if (apiResponse.getCode() == 400){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    if (fbaPlanOrder1.getIsDeliver() == 1){
                        //根据头程货件单号查询货件详情信息
                        params.put("codeShipment",fbaBox.getCodeShipment());
                        List<FbaBoxDetail> queryList = fbaBoxDetailMapper.select(params);
                        //直接进入变成头程装箱，已装箱状态，箱规参照系统默认或头程计划单选择的箱规标准
                        generate(queryList,fbaBox,userInfo,apiResponse,gaugeMaintenanceList,fbaPlanOrderDetailList);
                        if (apiResponse.getCode() == 400){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                    }
                }

                fbaPlanOrder1.setState("1");
                fbaPlanOrder1.setAuditTime(new Date());
                fbaPlanOrder1.setAuditUser(userInfo.getUserId());
                fbaPlanOrderMapper.update(fbaPlanOrder1);
            }
            apiResponse.setCode(0);
            apiResponse.setMsg("审核成功!");
        } catch (Exception e) {
            apiLogService.addApiLog("api","AddParcel","body：" + params.get("infoItems").toString(),"",500, apiResponse.getMsg());
            apiResponse.setCode(500);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return  apiResponse;
    }

    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse addParcelZD(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        CreateInboundShipmentPlanRequest body;
        Address address;
        PrepDetailsList prepDetails;
        PrepDetails prepDetails1;
        InboundShipmentPlanRequestItemList inboundShipmentPlanRequestItems = null;
        InboundShipmentPlanRequestItem inboundShipmentPlanRequestItem;
        List<FbaPlanOrderDetail> fbaPlanOrderDetailList;
        List<FbaPlanOrderDetail> fbaPlanOrderDetailTotal;
        Map<String, Object> params1;
        SellerSecretsVO secretsVO;
        InboundShipmentRequest inboundShipmentRequest = null;
        InboundShipmentHeader inboundShipmentHeader = null;
        InboundShipmentItemList inboundShipmentItems = null;
        InboundShipmentItem inboundShipmentItem = null;
        List<FbaPlanOrder> list = null;
        List<FbaShipment> data = null;
        FbaShipment fbaShipment1;
        Address harvestAddress = null;
        UserInfo userInfo;
        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaPlanOrder.class);

            prepDetails = new PrepDetailsList();


            for (FbaPlanOrder fbaPlanOrder : list) {
                FbaPlanOrder fbaPlanOrder1 = fbaPlanOrderMapper.queryFirstByGuid(fbaPlanOrder.getGuid());
                if (fbaPlanOrder1 == null){
                    apiResponse.setMsg(fbaPlanOrder.getCode() + "头程计划不存在,请刷新后再次操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                if (fbaPlanOrder1.getState().equals("1")){
                    apiResponse.setMsg(fbaPlanOrder.getCode() + "头程计划已审核,请刷新后再次操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                userInfo = userInfoMapper.findByUserId(fbaPlanOrder1.getaUser());
                if ("自动".equals(fbaPlanOrder1.getCreationMethod())) {
                    body = new CreateInboundShipmentPlanRequest();

                    if (userInfo == null){
                        apiResponse.setMsg(fbaPlanOrder1.getCode() + "头程计划名下的用户不存在!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    //查询网店信息
                    AmazonShop  amazonShop = amazonShopMapper.findAmazonShopByGuid(fbaPlanOrder1.getSellerId());
                    if (amazonShop != null) {
                        address = new Address();
                        secretsVO = new SellerSecretsVO();
                        getAmazonShop(amazonShop, address, secretsVO);

                        //查询头程计划详情信息
                        params1 = new HashMap<String, Object>();
                        params1.put("code", fbaPlanOrder1.getCode());
                        fbaPlanOrderDetailList = fbaPlanOrderDetailMapper.queryList(params1);
                        fbaPlanOrderDetailTotal = fbaPlanOrderDetailMapper.queryListSum(params1);
                        if (fbaPlanOrderDetailTotal.size() != 0) {
                            inboundShipmentPlanRequestItems = new InboundShipmentPlanRequestItemList();
                            for (FbaPlanOrderDetail fbaPlanOrderDetail : fbaPlanOrderDetailTotal) {
                                inboundShipmentPlanRequestItem = new InboundShipmentPlanRequestItem();
                                inboundShipmentPlanRequestItem.setSellerSKU(fbaPlanOrderDetail.getSku());
                                inboundShipmentPlanRequestItem.setASIN(fbaPlanOrderDetail.getAsin());
                                inboundShipmentPlanRequestItem.setCondition(Condition.NEWITEM);
                                inboundShipmentPlanRequestItem.setQuantity(fbaPlanOrderDetail.getNumPlanDeliver());
                                //判断有多少个包装要求
                                String[] prepInstructionList = fbaPlanOrderDetail.getPrepInstructionList().split(",");
                                for (String prepInstruction : prepInstructionList){
                                    prepDetails1 = new PrepDetails();
                                    prepDetails1.setPrepInstruction(PrepInstruction.fromValue(prepInstruction));
                                    prepDetails1.setPrepOwner(PrepOwner.SELLER);
                                    prepDetails.add(prepDetails1);
                                }
                                inboundShipmentPlanRequestItem.setPrepDetailsList(prepDetails);
                                inboundShipmentPlanRequestItems.add(inboundShipmentPlanRequestItem);
                            }

                            body.setShipFromAddress(address);
                            body.setLabelPrepPreference(LabelPrepPreference.SELLER_LABEL);
                            if (!amazonShop.getRegionName().equals("欧洲") && !amazonShop.getRegionName().equals("北美")){
                                apiResponse.setCode(400);
                                apiResponse.setMsg("当前只允许欧洲和北美站,请重新操作!");
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }
                            //根据站点对应的货件站点
                            AmazonSellerUrlEnum[] AmazonSellerUrlEnumList = AmazonSellerUrlEnum.values();
                            for (AmazonSellerUrlEnum amazonSellerUrlEnum : AmazonSellerUrlEnumList){
                                if(amazonShop.getCountryName().equals(amazonSellerUrlEnum.getCnName())){
                                    body.setShipToCountryCode(amazonSellerUrlEnum.getCode());
                                }
                            }
                            body.setInboundShipmentPlanRequestItems(inboundShipmentPlanRequestItems);
                            //创建头程计划
                            FbaInboundApi api = Helper.buildApi(secretsVO, FbaInboundApi.class);
                            CreateInboundShipmentPlanResponse response = api.createInboundShipmentPlan(body);
                            apiLogService.addApiLog("api","AddParcel","body：" + body.toString()+","+"response:"+response.getPayload(),"",0, "创建货件createInboundShipmentPlan成功!");
                            CreateInboundShipmentPlanResult createInboundShipmentPlanResult = response.getPayload();
                            InboundShipmentPlanList inboundShipmentPlans = createInboundShipmentPlanResult.getInboundShipmentPlans();
                            //提示
                            if (params.get("type").equals("0")){
                                data = new ArrayList<>();
                                for (InboundShipmentPlan inboundShipmentPlan : inboundShipmentPlans) {
                                    fbaShipment1 = new FbaShipment();
                                    fbaShipment1.setDestinationFulfillmentCenterId(inboundShipmentPlan.getDestinationFulfillmentCenterId());
                                    fbaShipment1.setShipmentId(inboundShipmentPlan.getShipmentId());
                                    fbaShipment1.setCurrencyAmount(inboundShipmentPlan.getEstimatedBoxContentsFee().getTotalFee().getValue());
                                    fbaShipment1.setCurrency(inboundShipmentPlan.getEstimatedBoxContentsFee().getTotalFee().getCurrencyCode().getValue());
                                    data.add(fbaShipment1);
                                }
                                apiResponse.setCode(200);
                                apiResponse.setData(data);
//                                if (inboundShipmentPlans.size()>1){
//                                    apiResponse.setMsg("该数据已分仓请联系管理员处理!");
//                                }
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }else {
                                if (inboundShipmentPlans.size() > 1) {
//                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

                                    //重新计算费用逻辑(多个就说明分仓,根据反馈回来的数据进行分离头程计划数据)
                                separateWarehouse(inboundShipmentPlans,fbaPlanOrder1,apiResponse,
                                        harvestAddress,userInfo,address,inboundShipmentRequest,
                                        inboundShipmentHeader,inboundShipmentItems,inboundShipmentItem,fbaPlanOrderDetailList,
                                        prepDetails,amazonShop,api);
                                    return apiResponse;

                                } else {
                                    for (InboundShipmentPlan inboundShipmentPlan : inboundShipmentPlans) {
                                        //收货地址信息
                                        harvestAddress = inboundShipmentPlan.getShipToAddress();

                                        //新增货件单
                                        FbaShipment fbaShipment = new FbaShipment();
                                        addShipment(fbaPlanOrder1, harvestAddress, inboundShipmentPlan, fbaShipment, userInfo, apiResponse);
                                        if (apiResponse.getCode() == 400) {
                                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                            return apiResponse;
                                        }
                                        inboundShipmentRequest = new InboundShipmentRequest();

                                        inboundShipmentHeader = new InboundShipmentHeader();
                                        inboundShipmentHeader.setShipmentName(inboundShipmentPlan.getShipmentId() + "-" + inboundShipmentPlan.getDestinationFulfillmentCenterId());
                                        inboundShipmentHeader.setShipFromAddress(address);
                                        inboundShipmentHeader.setDestinationFulfillmentCenterId(inboundShipmentPlan.getDestinationFulfillmentCenterId());
                                        inboundShipmentHeader.setShipmentStatus(ShipmentStatus.WORKING);
                                        inboundShipmentHeader.setLabelPrepPreference(LabelPrepPreference.SELLER_LABEL);
                                        inboundShipmentHeader.setIntendedBoxContentsSource(IntendedBoxContentsSource.FEED);

                                        inboundShipmentItems = new InboundShipmentItemList();

                                        for (InboundShipmentPlanItem inboundShipmentPlanItem : inboundShipmentPlan.getItems()) {
                                            //拿到对应的头程计划详情信息
                                            List<FbaPlanOrderDetail> fbaPlanOrderDetailList1 = fbaPlanOrderDetailList.stream().filter(
                                                    fbaPlanOrderDetail ->
                                                            fbaPlanOrderDetail.getSku().equals(inboundShipmentPlanItem.getSellerSKU())
                                                                    && fbaPlanOrderDetail.getFnsku().equals(inboundShipmentPlanItem.getFulfillmentNetworkSKU())
                                            ).collect(Collectors.toList());
                                            if (fbaPlanOrderDetailList1.size() == 0) {
                                                apiResponse.setMsg(fbaPlanOrder1.getCode() + "头程计划名下的商品信息不存在!");
                                                apiResponse.setCode(400);
                                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                                return apiResponse;
                                            } else {
                                                for (FbaPlanOrderDetail fbaPlanOrderDetail : fbaPlanOrderDetailList1) {
                                                    //新增货件详情
                                                    addShipmentDetail(fbaPlanOrderDetail, fbaShipment, userInfo, apiResponse);
                                                    if (apiResponse.getCode() == 400) {
                                                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                                        return apiResponse;
                                                    }
                                                }
                                            }

                                            //设置第二步api商品信息
                                            inboundShipmentItem = new InboundShipmentItem();
                                            inboundShipmentItem.setSellerSKU(inboundShipmentPlanItem.getSellerSKU());
                                            inboundShipmentItem.setFulfillmentNetworkSKU(inboundShipmentPlanItem.getFulfillmentNetworkSKU());
                                            inboundShipmentItem.setQuantityShipped(inboundShipmentPlanItem.getQuantity());
                                            inboundShipmentItem.setPrepDetailsList(prepDetails);
                                            inboundShipmentItems.add(inboundShipmentItem);
                                        }

                                        inboundShipmentRequest.setInboundShipmentHeader(inboundShipmentHeader);
                                        inboundShipmentRequest.setInboundShipmentItems(inboundShipmentItems);
                                        inboundShipmentRequest.setMarketplaceId(amazonShop.getMarketplaceIds());
                                        InboundShipmentResponse inboundShipmentResponse = api.createInboundShipment(inboundShipmentRequest, inboundShipmentPlan.getShipmentId());
                                        apiLogService.addApiLog("api", "AddParcel", "inboundShipmentResponse：" + inboundShipmentResponse.toString() + "," + "response:" + inboundShipmentResponse.getPayload(), "", 0, "创建货件createInboundShipment成功!");
                                    }
                                }
                            }
                        } else {
                            apiResponse.setMsg(fbaPlanOrder1.getCode() + "头程计划名下的商品信息不存在!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                    } else {
                        apiResponse.setMsg(fbaPlanOrder1.getCode() + "头程计划名下店铺信息为空!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                } else {
                    apiResponse.setMsg(fbaPlanOrder.getCode() + "头程计划数据已更变,请刷新后再次操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

//                fbaPlanOrder1.setUpdateTime(new Date());
                fbaPlanOrder1.setState("1");
                fbaPlanOrder1.setAuditTime(new Date());
                fbaPlanOrder1.setAuditUser(userInfo.getUserId());
                fbaPlanOrderMapper.update(fbaPlanOrder1);
            }
            apiResponse.setCode(0);
            apiResponse.setMsg("审核成功!");
        } catch (ApiException e) {
            if (e.getMessage().equals("Error getting LWA Access Token")) {
                apiResponse.setMsg("获取该网店令牌失败,请核实该店铺是否有权限!");
            } else if (e.getMessage().equals("Bad Request")) {
                apiResponse.setMsg("上传亚马逊货件数据出错,请核实数据再操作!");
            }else if (e.getMessage().contains("PrepInstruction ") && e.getMessage().contains("GetPrepInstructionsForSKU")){
                apiResponse.setMsg("请核实该商品中的包装要求,前往网店商品信息手动刷新!");
            }
            apiResponse.setMessage(e.getResponseBody());
            apiResponse.setCode(500);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return  apiResponse;
    }



    /**
     * 头程货件回退(取消货件)
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse cancelParcel(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<FbaShipment> list;
        List<FbaShipment> listNew;
        InboundShipmentRequest body;
        Address address;
        InboundShipmentHeader inboundShipmentHeader;
        InboundShipmentItemList inboundShipmentItems;
        Map<String, Object> params1;
        List<FbaShipmentDetail> fbaShipmentDetailList;
        InboundShipmentItem inboundShipmentItem ;
        SellerSecretsVO secretsVO;
        FbaInboundApi api;
        Map<String, Object> paramsNew;
        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaShipment.class);

            for (FbaShipment fbaShipment : list) {
                //删除货件信息  删除货件和详情 然后再更改计划单的状态
                try {
                    if ("自动".equals(fbaShipment.getCreationMethod())) {
                        paramsNew = new HashMap<String, Object>();
                        paramsNew.put("codePlan",fbaShipment.getCodePlan());
                        listNew = fbaShipmentMapper.findFbaShipment(paramsNew);
                        if (listNew.size() > 1){
                            apiResponse.setMsg("自动头程超出多单不允许回退,回退失败!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                    }
                    fbaShipmentMapper.delete(fbaShipment.getGuid());

                    fbaShipmentDetailMapper.deleteCodeShipmentOrder(fbaShipment.getCode());

                    fbaPlanOrderMapper.updateCode(fbaShipment.getCodePlan());
                }catch (Exception e){
                    apiResponse.setMsg("回退失败!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                if ("自动".equals(fbaShipment.getCreationMethod())) {
                    body = new InboundShipmentRequest();

                    //查询网店信息
                    AmazonShop  amazonShop = amazonShopMapper.findAmazonShopByGuid(fbaShipment.getSellerId());
                    if (amazonShop != null) {
                        address = new Address();
                        secretsVO = new SellerSecretsVO();
                        getAmazonShop(amazonShop, address, secretsVO);

                        inboundShipmentHeader = new InboundShipmentHeader();
                        inboundShipmentHeader.setShipmentName(fbaShipment.getShipmentId() + "-" + fbaShipment.getDestinationFulfillmentCenterId());
                        inboundShipmentHeader.setShipFromAddress(address);
                        inboundShipmentHeader.setDestinationFulfillmentCenterId(fbaShipment.getDestinationFulfillmentCenterId());
                        inboundShipmentHeader.setShipmentStatus(ShipmentStatus.CANCELLED);
                        inboundShipmentHeader.setLabelPrepPreference(LabelPrepPreference.SELLER_LABEL);
                        inboundShipmentHeader.setIntendedBoxContentsSource(IntendedBoxContentsSource.FEED);

                        inboundShipmentItems = new InboundShipmentItemList();
                        //查询头程计划详情信息
                        params1 = new HashMap<String, Object>();
                        params1.put("code", fbaShipment.getCode());
                        fbaShipmentDetailList = fbaShipmentDetailMapper.queryList(params1);
                        for (FbaShipmentDetail fbaShipmentDetail : fbaShipmentDetailList) {
                            inboundShipmentItem = new InboundShipmentItem();
                            inboundShipmentItem.setSellerSKU(fbaShipmentDetail.getSku());
                            inboundShipmentItem.setFulfillmentNetworkSKU(fbaShipmentDetail.getFnsku());
                            inboundShipmentItem.setQuantityShipped(fbaShipmentDetail.getNumPlanDeliver());
                            inboundShipmentItems.add(inboundShipmentItem);
                        }

                        body.setInboundShipmentHeader(inboundShipmentHeader);
                        body.setInboundShipmentItems(inboundShipmentItems);
                        body.setMarketplaceId(amazonShop.getMarketplaceIds());
                        api = Helper.buildApi(secretsVO, FbaInboundApi.class);
                        InboundShipmentResponse response = api.updateInboundShipment(body, fbaShipment.getShipmentId());
                        apiLogService.addApiLog("api","CancelParcel","body：" + body.toString()+","+"response:"+response.getPayload(),"",0, "取消货件updateInboundShipment成功!");
                    } else {
                        apiResponse.setMsg(fbaShipment.getCode() + "头程货件名下店铺信息为空!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                }
            }
            apiResponse.setCode(0);
            apiResponse.setMsg("回退成功!");
        } catch (Exception e) {
            if (e.getMessage().equals("Error getting LWA Access Token")) {
                apiResponse.setMsg("获取该网店令牌失败,请核实该店铺是否有权限!");
            }else if (e.getMessage().equals("Bad Request")) {
                apiResponse.setMsg("上传亚马逊货件数据出错,请核实数据再操作!");
            }
            apiLogService.addApiLog("api","AddParcel","body：" + params.get("infoItems").toString(),"",500, apiResponse.getMsg());
            apiResponse.setCode(500);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }


    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse placeOrder(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<FbaBox> list;
        Map<String, Object> params3;
        UserInfo userInfo;
        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaBox.class);
            for (FbaBox fbaBox : list) {
                userInfo = userInfoMapper.findByUserId(params.get("userId").toString());
                if (userInfo == null){
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的用户不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                fbaBox = fbaBoxMapper.queryFirstByGuid(fbaBox.getGuid());
                if (fbaBox == null){
                    apiResponse.setMsg(fbaBox.getCode() + "头程装箱单不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                params3 = new HashMap<String, Object>();
                params3.put("codeShipment",fbaBox.getCodeShipment());
                List<FbaBoxDetail> fbaBoxDetail1 = fbaBoxDetailMapper.findFbaBoxDetail(params3);
                if (fbaBoxDetail1.size() == 0){
                    apiResponse.setMsg(fbaBox.getCode() + "装箱失败,未填写装箱数据!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

//                    fbaBox.setUpdateUser(userInfo.getUserId());
                fbaBox.setUpdateUser(userInfo.getUserName());
                fbaBox.setStateName("已装箱");
                fbaBox.setUpdateTime(new Date());
                fbaBox.setState("2");
                fbaBoxMapper.updateByGuid(fbaBox);
            }
            apiResponse.setCode(0);
            apiResponse.setMsg("上传箱子数据成功!");
        }catch (Exception e) {
            apiResponse.setMsg("上传箱子数据失败!");
            apiLogService.addApiLog("api","PlaceOrder","body：" + params.get("infoItems").toString(),"",500, apiResponse.getMsg());
            apiResponse.setCode(500);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }


    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse placeOrderZd(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<FbaBox> list;
        Map<String, Object> params3;
        UserInfo userInfo;
        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaBox.class);
            for (FbaBox fbaBox : list) {
                userInfo = userInfoMapper.findByUserId(params.get("userId").toString());
                if (userInfo == null){
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的用户不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                fbaBox = fbaBoxMapper.queryFirstByGuid(fbaBox.getGuid());
                if (fbaBox == null){
                    apiResponse.setMsg(fbaBox.getCode() + "头程装箱单不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                params3 = new HashMap<String, Object>();
                params3.put("codeShipment",fbaBox.getCodeShipment());
                List<FbaBoxDetail> fbaBoxDetail1 = fbaBoxDetailMapper.findFbaBoxDetail(params3);
                if (fbaBoxDetail1.size() == 0){
                    apiResponse.setMsg(fbaBox.getCode() + "装箱失败,未填写装箱数据!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                fbaBox.setUpdateUser(userInfo.getUserName());
                fbaBox.setStateName("已装箱");
                fbaBox.setUpdateTime(new Date());
                fbaBox.setState("2");
                fbaBoxMapper.updateByGuid(fbaBox);
            }
            apiResponse.setCode(0);
            apiResponse.setMsg("上传箱子数据成功!");
        }catch (Exception e) {
            if (e.getMessage().equals("Error getting LWA Access Token")) {
                apiResponse.setMsg("获取该网店令牌失败,请核实该店铺是否有权限!");
            }else if (e.getMessage().equals("Bad Request")) {
                apiResponse.setMsg("上传亚马逊货件数据出错,请核实数据再操作!");
            } else {
                apiResponse.setMsg("上传箱子数据失败!");
            }
            apiLogService.addApiLog("api","PlaceOrder","body：" + params.get("infoItems").toString(),"",500, apiResponse.getMsg());
            apiResponse.setCode(500);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }


    /**
     * 头程货件修改或者删除
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse deleteOrModify(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<FbaBox> list;
        InboundShipmentRequest body;
        Address address;
        InboundShipmentHeader inboundShipmentHeader;
        InboundShipmentItemList inboundShipmentItems;
        Map<String, Object> params1;
        Map<String, Object> params2;
        InboundShipmentItem inboundShipmentItem ;
        SellerSecretsVO secretsVO;
        FbaInboundApi api;
        FbaDevanningDetail fbaDevanningDetail;
        UserInfo userInfo;
        String msg = "";
        List<FbaBoxDetail> fbaBoxDetailList;
        List<FbaBox> fbaBoxList;
        List<FbaBoxDetail> fbaBoxDetailListNew = null;
        AccountCountForCompany logisticsAccount;
        AccountCountForCompany operationAccount;
        AccountCountForCompany warehousingAccount;
        Double transparencyProject;
        Integer tCNum;
        Map<Integer,Integer> numBiDc;
        String numRealityDeliver;
        Double boxProject = 0.0;
        Double priceTranPredict1 = 0.0;
        SysAccountBandDept sysAccountBandDept;
        FbaPlanOrder fbaPlanOrder1;
        List<AccountDetailedForCompany> accountList;
        StringBuffer stringBuffer = null;
        FbaShipment fbaShipment;
        FbaPlanOrder fbaPlanOrder;
        Map<String, Object> paramsNew;
        List<FbaShipment> listNew;
        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaBox.class);

            for (FbaBox fbaBox : list) {
                accountList =new ArrayList<>();
                userInfo= userInfoMapper.findByUserId(params.get("userId").toString());
                if (userInfo == null){
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的用户不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                FbaBox fbaBox1 = fbaBoxMapper.queryFirstByGuid(fbaBox.getGuid());
                if (fbaBox1 == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程装箱单不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                operationAccount = accountCountForCompanyMapper.queryFirstByVGsBm(fbaBox1.getCodeCompany());
                if (operationAccount == null){
                    apiResponse.setMsg("运营公司实时资金不存在,请核实后再操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                //查询仓储部绑定账户
                sysAccountBandDept = sysAccountBandDeptMapper.findByAccountId("CCB");
                if (sysAccountBandDept == null){
                    apiResponse.setMsg("仓储部绑定账户未启用或不存在,请核实后再操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                // 仓储部绑定账户增加物流费用
                warehousingAccount = accountCountForCompanyMapper.queryFirstByVGsBm(sysAccountBandDept.getvGsBm());
                if (warehousingAccount == null){
                    apiResponse.setMsg("仓储部实时资金不存在,请核实后再操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                //计算装箱物料费 + 透明计划贴标费
                boxProject = Double.valueOf(fbaBox1.getNumBox()) * 15;

                if ("0".equals(params.get("num").toString())) {
                    if (!fbaBox1.getState().equals("3")) {
                        apiResponse.setMsg(fbaBox.getCode() + "状态不是FBA已导入,请核实后在操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    //修改发货
                    fbaBox1.setState(params.get("state").toString());
                    fbaBox1.setStateName("已完成");
                    fbaBox1.setStatePrint("4");
                    fbaBox1.setStatePrintName("箱标未打印");
                    fbaBox1.setAuditUser(userInfo.getUserName());
                    fbaBox1.setAuditTime(new Date());

                    //查询头程货件详情信息
                    params1 = new HashMap<String, Object>();
                    //头程计划单下所有箱子数据
                    params1.put("codeBox1",fbaBox.getCode());
                    fbaBoxDetailList = fbaBoxDetailMapper.findFbaBoxDetail(params1);

                    if (fbaBoxDetailList.size() == 0){
                        apiResponse.setMsg("头程单名下的商品信息不存在!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

                    for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailList) {
                        if (fbaBoxDetai.getPriceSingleBoxReq().compareTo(fbaBox1.getPriceSingleBoxReq()) > 0) {
                            apiResponse.setMsg("FBA编号:" + fbaBox1.getShipmentId() + ",第" + (fbaBoxDetai.getBoxIndex() + 1) + "箱,超过单箱采购价要求,请核实");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                        if (fbaBoxDetai.getPriceSingleBoxReq().compareTo(fbaBox1.getPriceSingleBoxReqZd()) < 0) {
                            apiResponse.setMsg("FBA编号:" + fbaBox1.getShipmentId() + ",第" + (fbaBoxDetai.getBoxIndex() + 1) + "箱,小于单箱最低采购价要求,请核实");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                    }
                    transparencyProject = 0.0;
                    tCNum = 0;
                    numBiDc = new HashMap<>();
                    if (fbaBoxDetailList.size() != 0) {
                        for (int i = 0; i < fbaBoxDetailList.size(); i++) {
                            fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(i).getProductInfo(), FbaBoxDetail.class);
                            for (int j = 0; j < fbaBoxDetailListNew.size(); j++) {
                                if (numBiDc.get(j) == null) {
                                    numBiDc.put(j, new Integer(fbaBoxDetailListNew.get(j).getNumRealityDeliver().equals("") ? "0" : fbaBoxDetailListNew.get(j).getNumRealityDeliver()));
                                } else {
                                    numBiDc.put(j, numBiDc.get(j) + (new Integer(fbaBoxDetailListNew.get(j).getNumRealityDeliver().equals("") ? "0" : fbaBoxDetailListNew.get(j).getNumRealityDeliver())));
                                }
                            }
                        }
                        fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(0).getProductInfo(), FbaBoxDetail.class);
                        stringBuffer = new StringBuffer();
                        for (int j = 0; j < fbaBoxDetailListNew.size(); j++) {
                            //修改库存总数量
                            updateNum(fbaBox1, fbaBoxDetailListNew.get(j), apiResponse, userInfo, 0, numBiDc.get(j));
                            if (apiResponse.getCode() == 400) {
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }
                            if (!fbaBoxDetailListNew.get(j).getvDFilesDefault().equals("无附件")) {
                                //详情备注赋值
                                stringBuffer.append(fbaBoxDetailListNew.get(j).getCommodityCode() + ",数量" + numBiDc.get(j) + "个,");
                                //累加透明计划贴标费
                                transparencyProject = transparencyProject + (Double.valueOf(numBiDc.get(j)) * (0.6));
                            }
                            if (fbaBoxDetailListNew.get(j).getIsSign() != null) {
                                if (fbaBoxDetailListNew.get(j).getIsSign().equals("是")) {
                                    tCNum = tCNum + numBiDc.get(j);
                                }
                            }
                        }
                    }

                    //透明计划商品的总发货数量。取值=透明计划标记为“是”的商品实际发货数量总和
                    fbaBox1.settCNum(tCNum);
                    fbaBoxMapper.updateByGuid(fbaBox1);

                    if (fbaBox1.getIsDeliver() != 1) {
                        //头程冻结的实际物流费用
                        priceTranPredict1 = Double.valueOf(fbaBox1.getActualLogisticsFreight().toString());

//                    查询物流部账号
                        sysAccountBandDept = sysAccountBandDeptMapper.findByAccountId("WLB");
                        if (sysAccountBandDept == null) {
                            apiResponse.setMsg("物流部门绑定账户未启用或不存在,请核实后再操作!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                        // 物流公司增加物流费用
                        logisticsAccount = accountCountForCompanyMapper.queryFirstByVGsBm(sysAccountBandDept.getvGsBm());
                        if (logisticsAccount == null) {
                            apiResponse.setMsg("物流公司实时资金不存在,请核实后再操作!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }

//                    资金流水(运营公司-物流部 头程物流费)
                        addAccountDetailedForCompany(logisticsAccount, operationAccount, userInfo, -priceTranPredict1,
                                "头程物流费，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + "," + fbaBox1.getShipmentId() + "," + fbaBox1.getNameLogsticsWay(),
                                "物流服务→头程运费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                        );
                        //运营公司扣减头程物流费
                        operationAccount.setfJe(operationAccount.getfJe() - priceTranPredict1);

                        //资金流水(物流部 -运营公司头程物流费)
                        addAccountDetailedForCompany(operationAccount, logisticsAccount, userInfo, priceTranPredict1,
                                "头程物流费，头程计划单:" + fbaBox1.getCodePlan()+ ",头程装箱单:" +fbaBox1.getCode()  + "," + fbaBox1.getShipmentId() + "," + fbaBox1.getNameLogsticsWay(),
                                "物流服务→头程运费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                        );
                        //物流部新增头程物流费
                        logisticsAccount.setfJe(logisticsAccount.getfJe() + priceTranPredict1);
                        accountCountForCompanyMapper.updateAccountCountForCompany(logisticsAccount);

                        //资金流水(运营公司-仓储部 纸箱包装费)
                        addAccountDetailedForCompany(warehousingAccount, operationAccount, userInfo, -boxProject,
                                "纸箱费，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + ",纸箱个数" + fbaBox1.getNumBox(),
                                "仓储服务→纸箱费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                        );
                        //运营公司扣减纸箱包装费
                        operationAccount.setfJe(operationAccount.getfJe() - boxProject);

                        //资金流水(仓储部-运营公司 纸箱包装费)
                        addAccountDetailedForCompany(operationAccount, warehousingAccount, userInfo, boxProject,
                                "纸箱费，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + ",纸箱个数" + fbaBox1.getNumBox(),
                                "仓储服务→纸箱费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                        );
                        //仓储部新增纸箱包装费
                        warehousingAccount.setfJe(warehousingAccount.getfJe() + boxProject);

                        if (stringBuffer.length() != 0) {
                            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                        }
                        if (transparencyProject != 0.0) {
                            //资金流水(运营公司-仓储部 透明计划贴标费用)
                            addAccountDetailedForCompany(warehousingAccount, operationAccount, userInfo, -transparencyProject,
                                    "透明计划贴标费用，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + "," + stringBuffer,
                                    "仓储服务→透明计划贴标费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                            );
                            //运营公司扣减 透明计划贴标费用
                            operationAccount.setfJe(operationAccount.getfJe() - transparencyProject);

                            //资金流水(仓储部-运营公司 透明计划贴标费用)
                            addAccountDetailedForCompany(operationAccount, warehousingAccount, userInfo, transparencyProject,
                                    "透明计划贴标费用，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + "," + stringBuffer,
                                    "仓储服务→透明计划贴标费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                            );
                            //仓储部新增 透明计划贴标费用
                            warehousingAccount.setfJe(warehousingAccount.getfJe() + transparencyProject);
                        }
                        //更新仓储部
                        accountCountForCompanyMapper.updateAccountCountForCompany(warehousingAccount);

                        //更新运营公司
                        accountCountForCompanyMapper.updateAccountCountForCompany(operationAccount);
                    }
                    //海外仓逻辑
                    if (fbaBox1.getIsDeliver() == 1){
                        addHwTailprogram(apiResponse,fbaBox1,fbaBoxDetailList,numBiDc);
                        if (apiResponse.getCode() == 400){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                    }
                } else if ("1".equals(params.get("num").toString())) {
                    if (fbaBox1.getState().equals("1")) {
                        apiResponse.setMsg(fbaBox.getCode() + "状态已审核,不允许拆箱,请核实后在操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    if (fbaBox1.getDeleted() == true) {
                        apiResponse.setMsg(fbaBox.getCode() + "状态已删除,不允许拆箱,请核实后在操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    FbaShipment fbaShipment1 = fbaShipmentMapper.queryFirstByCode(fbaBox.getCodeShipment());
                    if (fbaShipment1 == null){
                        apiResponse.setMsg("头程货件不存在!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    if ("自动".equals(fbaBox.getCreationMethod())) {
                        paramsNew = new HashMap<String, Object>();
                        paramsNew.put("codePlan",fbaBox1.getCodePlan());
                        listNew = fbaShipmentMapper.findFbaShipment(paramsNew);
                        if (listNew.size() > 1){
                            apiResponse.setMsg("自动头程超出多单不允许拆箱,拆箱失败!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                    }
                    FbaDevanning fbaDevanning = new FbaDevanning();
                    addDevanning(fbaBox1,params,fbaDevanning,userInfo,apiResponse,fbaShipment1,0);
                    if (apiResponse.getCode() == 400){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    //查询头程货件详情信息
                    params1 = new HashMap<String, Object>();
                    //头程计划单下所有箱子数据
                    params1.put("codeBox1",fbaBox.getCode());
                    fbaBoxDetailList = fbaBoxDetailMapper.findFbaBoxDetail(params1);

                    if (fbaBoxDetailList.size() == 0){
                        apiResponse.setMsg("头程单名下的商品信息不存在!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    if (fbaBoxDetailList.size() != 0) {
                        fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(0).getProductInfo(), FbaBoxDetail.class);
                        for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailListNew) {
                            //新增拆箱详情
                            fbaDevanningDetail = new FbaDevanningDetail();
                            addDevanningDetail(fbaBoxDetai,fbaDevanningDetail,fbaDevanning,userInfo,apiResponse,0);
                            if (apiResponse.getCode() == 400){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }
                        }
                    }

                    fbaBox1.setDeleted(true);
                    //删除装箱单
                    fbaBoxMapper.updateByGuid(fbaBox1);

//                    //删除装箱单详情
//                    fbaBoxDetailMapper.deleteCodeBox(fbaBox1.getCode());

                    params2 = new HashMap<String, Object>();
                    params2.put("codeShipment",fbaBox.getCodeShipment());
                    fbaBoxList = fbaBoxMapper.findFbaBox(params2);
                    if (fbaBoxList.size() == 0){
                        fbaShipment = new FbaShipment();
                        fbaShipment.setCode(fbaBox1.getCodeShipment());
                        fbaShipment.setDeleted(true);
                        //删除货件
                        fbaShipmentMapper.updateByCode(fbaShipment);

                        fbaPlanOrder = new FbaPlanOrder();
                        fbaPlanOrder.setCode(fbaBox1.getCodePlan());
                        fbaPlanOrder.setDeleted(true);
                        //删除头程计划单状态
                        fbaPlanOrderMapper.updateByCode(fbaPlanOrder);
                    }
                } else if ("2".equals(params.get("num").toString())) {
                    if (fbaBox1.getState().equals("1")) {
                        apiResponse.setMsg(fbaBox.getCode() + "状态已审核,不允许取消,请核实后在操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    if (fbaBox1.getDeleted() == true) {
                        apiResponse.setMsg(fbaBox.getCode() + "状态已删除,不允许取消,请核实后在操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    FbaCancel fbaCancel = new FbaCancel();
                    addCancel(fbaBox1,params,fbaCancel,userInfo,apiResponse);
                    if (apiResponse.getCode() == 400){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

                    fbaBox1.setDeleted(true);
                    //删除装箱单
                    fbaBoxMapper.updateByGuid(fbaBox1);

                    params2 = new HashMap<String, Object>();
                    params2.put("codeShipment",fbaBox.getCodeShipment());
                    fbaBoxList = fbaBoxMapper.findFbaBox(params2);
                    if (fbaBoxList.size() == 0){
                        fbaShipment = new FbaShipment();
                        fbaShipment.setCode(fbaBox1.getCodeShipment());
                        fbaShipment.setDeleted(true);
                        //删除货件
                        fbaShipmentMapper.updateByCode(fbaShipment);

                        fbaPlanOrder = new FbaPlanOrder();
                        fbaPlanOrder.setCode(fbaBox1.getCodePlan());
                        fbaPlanOrder.setDeleted(true);
                        //删除头程计划单状态
                        fbaPlanOrderMapper.updateByCode(fbaPlanOrder);
                    }
                    //查询头程货件详情信息
                    params1 = new HashMap<String, Object>();
                    params1.put("codeBox1",fbaBox.getCode());
                    fbaBoxDetailList = fbaBoxDetailMapper.findFbaBoxDetail(params1);

                    if (fbaBoxDetailList.size() == 0){
                        apiResponse.setMsg("头程单名下的商品信息不存在!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

                    if (fbaBoxDetailList.size() != 0) {
                        fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(0).getProductInfo(), FbaBoxDetail.class);
                        for (int j = 0; j < fbaBoxDetailListNew.size(); j++) {
                            //修改库存总数量
                            updateNum(fbaBox1,fbaBoxDetailListNew.get(j), apiResponse, userInfo, 2, null);
                            if (apiResponse.getCode() == 400) {
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }
                        }
                    }
                }
                try {
                    if (accountList.size() != 0){
                        businessMapper.insertBatchNew(accountList);
                    }
                }catch (Exception e){
                    apiResponse.setMsg("新增账户流水单失败!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }


                if (!"0".equals(params.get("num").toString())) {
                    if ("自动".equals(fbaBox.getCreationMethod())) {
                        body = new InboundShipmentRequest();

                        //查询网店信息
                        AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid(fbaBox.getSellerId());
                        if (amazonShop != null) {
                            address = new Address();
                            secretsVO = new SellerSecretsVO();
                            getAmazonShop(amazonShop, address, secretsVO);

                            inboundShipmentHeader = new InboundShipmentHeader();
                            inboundShipmentHeader.setShipmentName(fbaBox.getShipmentId() + "-" + fbaBox.getDestinationFulfillmentCenterId());
                            inboundShipmentHeader.setShipFromAddress(address);
                            inboundShipmentHeader.setDestinationFulfillmentCenterId(fbaBox.getDestinationFulfillmentCenterId());
                            if ("0".equals(params.get("num").toString())) {
                                inboundShipmentHeader.setShipmentStatus(ShipmentStatus.SHIPPED);
                            } else {
                                inboundShipmentHeader.setShipmentStatus(ShipmentStatus.CANCELLED);
                            }
                            inboundShipmentHeader.setLabelPrepPreference(LabelPrepPreference.SELLER_LABEL);
                            inboundShipmentHeader.setIntendedBoxContentsSource(IntendedBoxContentsSource.FEED);

                            inboundShipmentItems = new InboundShipmentItemList();
                            //查询头程货件详情信息
                            params1 = new HashMap<String, Object>();
                            //头程计划单下所有箱子数据
                            params1.put("codeBox1", fbaBox.getCode());
                            fbaBoxDetailList = fbaBoxDetailMapper.findFbaBoxDetail(params1);

                            if (fbaBoxDetailList.size() == 0) {
                                apiResponse.setMsg("头程单名下的商品信息不存在!");
                                apiResponse.setCode(400);
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }
                            if (fbaBoxDetailList.size() != 0) {
                                //将相同的sku、Asin、FnSku相加起来
                                Set<String> fnSkuList = new HashSet<>();
                                List<FbaBoxDetail> fbaBoxDetailListOld = new ArrayList<>();
                                for (FbaBoxDetail fbaBoxDetail : fbaBoxDetailList){
                                    fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetail.getProductInfo(), FbaBoxDetail.class);
                                    for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailListNew) {
                                        fnSkuList.add(fbaBoxDetai.getFnsku());
                                        fbaBoxDetailListOld.add(fbaBoxDetai);
                                    }
                                }

                                List<FbaBoxDetail> fbaBoxDetailListApi;
                                BigDecimal numPlanDeliver;
                                for (String fnSku : fnSkuList) {
                                    fbaBoxDetailListApi = fbaBoxDetailListOld.stream().filter(
                                            fbaBoxDetail1 -> fbaBoxDetail1.getFnsku().equals(fnSku)
                                    ).collect(Collectors.toList());
                                    numPlanDeliver = BigDecimal.ZERO;
                                    for (FbaBoxDetail fbaBoxDetail : fbaBoxDetailListApi){
                                        numPlanDeliver = numPlanDeliver.add(new BigDecimal(fbaBoxDetail.getNumRealityDeliver().equals("")?"0":fbaBoxDetail.getNumRealityDeliver()));
                                    }
                                    inboundShipmentItem = new InboundShipmentItem();
                                    inboundShipmentItem.setSellerSKU(fbaBoxDetailListApi.get(0).getSku());
                                    inboundShipmentItem.setFulfillmentNetworkSKU(fbaBoxDetailListApi.get(0).getFnsku());
                                    inboundShipmentItem.setQuantityShipped(Integer.valueOf(numPlanDeliver.toString()));
                                    inboundShipmentItems.add(inboundShipmentItem);
                                }
                            }

                            body.setInboundShipmentHeader(inboundShipmentHeader);
                            body.setInboundShipmentItems(inboundShipmentItems);
                            body.setMarketplaceId(amazonShop.getMarketplaceIds());
                            api = Helper.buildApi(secretsVO, FbaInboundApi.class);
                            InboundShipmentResponse response = api.updateInboundShipment(body, fbaBox.getShipmentId());
                            if ("0".equals(params.get("num").toString())) {
                                msg = "修改货件updateInboundShipment成功";
                            } else {
                                msg = "删除货件updateInboundShipment成功";
                            }
                            apiLogService.addApiLog("api", "DeleteOrModify", "body：" + body.toString() + "," + "response:" + response.getPayload(), "", 0, msg);
                        } else {
                            apiResponse.setMsg(fbaBox.getCode() + "头程单名下的店铺不存在!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                    }
                }
            }
            if ("0".equals(params.get("num").toString())){
                msg = "审核成功";
            } else if ("1".equals(params.get("num").toString())){
                msg = "拆箱成功";
            } else {
                msg = "取消成功";
            }
            apiResponse.setMsg(msg);
            apiResponse.setCode(0);
        } catch (ApiException e) {
            if (e.getMessage().equals("Error getting LWA Access Token")) {
                apiResponse.setMsg("获取该网店令牌失败,请核实该店铺是否有权限!");
            }else if (e.getMessage().equals("Bad Request")) {
                apiResponse.setMsg("上传亚马逊货件数据出错,请核实数据再操作!");
            } else {
                if ("0".equals(params.get("num").toString())){
                    apiResponse.setMsg("审核失败!");
                } else if ("1".equals(params.get("num").toString())){
                    apiResponse.setMsg("拆箱失败!");
                } else {
                    msg = "取消失败";
                }

            }
            logger.error("拆箱失敗，错误信息为：" + e.getResponseBody());
            apiLogService.addApiLog("api","DeleteOrModify","body：" + params.get("infoItems").toString(),"",500, apiResponse.getMsg());
            apiResponse.setCode(500);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }


    /**
     * 头程货件自动修改成发货状态
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse zdModify(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<FbaBox> list;
        PrepDetailsList prepDetails;
        PrepDetails prepDetails1;
        InboundShipmentRequest body;
        Address address;
        InboundShipmentHeader inboundShipmentHeader;
        InboundShipmentItemList inboundShipmentItems;
        Map<String, Object> params1;
        Map<String, Object> params2;
        InboundShipmentItem inboundShipmentItem ;
        SellerSecretsVO secretsVO;
        FbaInboundApi api;
        FbaDevanningDetail fbaDevanningDetail;
        UserInfo userInfo;
        String msg = "";
        List<FbaBoxDetail> fbaBoxDetailList;
        List<FbaBox> fbaBoxList;
        List<FbaBoxDetail> fbaBoxDetailListNew = null;
        AccountCountForCompany logisticsAccount;
        AccountCountForCompany operationAccount;
        AccountCountForCompany warehousingAccount;
        Double transparencyProject;
        String numRealityDeliver;
        Map<Integer,Integer> numBiDc;
        Double allCost = 0.0;
        Double boxProject = 0.0;
        Double priceTranPredict = 0.0;
        Double priceTranPredict1 = 0.0;
        SysAccountBandDept sysAccountBandDept;
        FbaPlanOrder fbaPlanOrder1;
        List<AccountDetailedForCompany> accountList;
        StringBuffer stringBuffer = null;
        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaBox.class);

            for (FbaBox fbaBox : list) {
                accountList =new ArrayList<>();
                userInfo= userInfoMapper.findByUserId(params.get("userId").toString());
                if (userInfo == null){
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的用户不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                FbaBox fbaBox1 = fbaBoxMapper.queryFirstByGuid(fbaBox.getGuid());
                if (fbaBox1 == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程装箱单不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                operationAccount = accountCountForCompanyMapper.queryFirstByVGsBm(fbaBox1.getCodeCompany());
                if (operationAccount == null){
                    apiResponse.setMsg("运营公司实时资金不存在,请核实后再操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                //查询仓储部绑定账户
                sysAccountBandDept = sysAccountBandDeptMapper.findByAccountId("CCB");
                if (sysAccountBandDept == null){
                    apiResponse.setMsg("仓储部绑定账户未启用或不存在,请核实后再操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                // 仓储部绑定账户增加物流费用
                warehousingAccount = accountCountForCompanyMapper.queryFirstByVGsBm(sysAccountBandDept.getvGsBm());
                if (warehousingAccount == null){
                    apiResponse.setMsg("仓储部实时资金不存在,请核实后再操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }


                //计算装箱物料费 + 透明计划贴标费
                boxProject = Double.valueOf(fbaBox1.getNumBox()) * 15;


                if (!"1".equals(params.get("num").toString())) {
                    if (!fbaBox1.getState().equals("3")) {
                        apiResponse.setMsg(fbaBox.getCode() + "状态不是FBA已导入,请核实后在操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    //修改发货
                    fbaBox1.setState(params.get("state").toString());
                    fbaBox1.setStateName("已完成");
                    fbaBox1.setStatePrint("4");
                    fbaBox1.setStatePrintName("箱标未打印");
                    fbaBox1.setAuditUser(userInfo.getUserName());
                    fbaBox1.setAuditTime(new Date());
                    fbaBoxMapper.updateByGuid(fbaBox1);

                    //查询头程货件详情信息
                    params1 = new HashMap<String, Object>();
//                    params1.put("codeShipment", fbaBox.getCodeShipment());
                    //头程计划单下所有箱子数据
                    params1.put("codeBox1",fbaBox.getCode());
                    fbaBoxDetailList = fbaBoxDetailMapper.findFbaBoxDetail(params1);

                    if (fbaBoxDetailList.size() == 0){
                        apiResponse.setMsg("头程单名下的商品信息不存在!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailList){
                        //当是自税的时候不需要判断
                        if (!fbaBox1.getNameLogsticsClearance().equals("自税")){
                            if (fbaBoxDetai.getPriceSingleBoxReq().compareTo(fbaBox1.getPriceSingleBoxReq()) > 0){
                                apiResponse.setMsg("FBA编号:"+fbaBox1.getShipmentId()+",第"+(fbaBoxDetai.getBoxIndex()+1)+"箱,超过单箱采购价要求,请核实");
                                apiResponse.setCode(400);
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }
                        }
                    }
                    transparencyProject = 0.0;
                    numBiDc = new HashMap<>();
                    if (fbaBoxDetailList.size() != 0) {
                        for (int i = 0; i < fbaBoxDetailList.size(); i++) {
                            fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(i).getProductInfo(), FbaBoxDetail.class);
                            for (int j = 0; j < fbaBoxDetailListNew.size(); j++) {
                                if (numBiDc.get(j) == null){
                                    numBiDc.put(j,new Integer(fbaBoxDetailListNew.get(j).getNumRealityDeliver().equals("")?"0":fbaBoxDetailListNew.get(j).getNumRealityDeliver()));
                                }else {
                                    numRealityDeliver = fbaBoxDetailListNew.get(j).getNumRealityDeliver().equals("")?"0":fbaBoxDetailListNew.get(j).getNumRealityDeliver();
                                    numBiDc.put(j, numBiDc.get(j) + (new Integer(numRealityDeliver)));
                                }
                            }
                        }
                        fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(0).getProductInfo(), FbaBoxDetail.class);
                        stringBuffer = new StringBuffer();
                        for (int j = 0; j < fbaBoxDetailListNew.size(); j++) {
                            //修改库存总数量
                            updateNum(fbaBox,fbaBoxDetailListNew.get(j),apiResponse,userInfo,0,numBiDc.get(j));
                            if (apiResponse.getCode() == 400){
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }
                            if (!fbaBoxDetailListNew.get(j).getvDFilesDefault().equals("无附件")){
                                //详情备注赋值
                                stringBuffer.append(fbaBoxDetailListNew.get(j).getCommodityCode()+",数量"+fbaBoxDetailListNew.get(j).getNumPlanDeliver()+"个,");
                                //累加透明计划贴标费
                                transparencyProject = transparencyProject + (Double.valueOf(fbaBoxDetailListNew.get(j).getNumPlanDeliver()) * (0.6));
                            }
                        }
                    }

                    allCost = transparencyProject + boxProject;
                    // 运营公司账户扣减物流费用  扣减装箱物料费 + 透明计划贴标费
                    priceTranPredict = Double.valueOf(fbaBox1.getPriceTranPredictPlan());
                    //头程冻结的预估物流费用
                    priceTranPredict1 = Double.valueOf(fbaBox1.getPriceTranPredictPlan1());

//                     扣除账户冻结资金
//                    operationAccount.setfDjJe(operationAccount.getfDjJe() - priceTranPredict);
                    accountCountForCompanyMapper.updateAccountCountForCompany(operationAccount);
//                    查询物流部账号
                    sysAccountBandDept = sysAccountBandDeptMapper.findByAccountId("WLB");
                    if (sysAccountBandDept == null){
                        apiResponse.setMsg("物流部门绑定账户未启用或不存在,请核实后再操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    // 物流公司增加物流费用
                    logisticsAccount = accountCountForCompanyMapper.queryFirstByVGsBm(sysAccountBandDept.getvGsBm());
                    if (logisticsAccount == null){
                        apiResponse.setMsg("物流公司实时资金不存在,请核实后再操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

//                    资金流水(运营公司-物流部 头程物流费)
                    addAccountDetailedForCompany(logisticsAccount,operationAccount, userInfo,-priceTranPredict,
                            "头程物流费，头程计划单:"+fbaBox1.getCodePlan()+","+fbaBox1.getShipmentId()+","+fbaBox1.getNameLogsticsWay(),
                            "审核","装箱单",1,fbaBox1.getNid(),fbaBox1.getCode(),fbaBox1.getGuid(),fbaBox1.getCreateTime(),accountList
                    );
                    //资金流水(物流部 -运营公司头程物流费)
                    addAccountDetailedForCompany(operationAccount,logisticsAccount, userInfo,priceTranPredict,
                            "头程物流费，头程计划单:"+fbaBox1.getCodePlan()+","+fbaBox1.getShipmentId()+","+fbaBox1.getNameLogsticsWay(),
                            "审核","装箱单",1,fbaBox1.getNid(),fbaBox1.getCode(),fbaBox1.getGuid(),fbaBox1.getCreateTime(),accountList
                    );
                    //资金流水(运营公司-仓储部 纸箱包装费)
                    addAccountDetailedForCompany(warehousingAccount,operationAccount, userInfo,-boxProject,
                            "纸箱费，头程计划单:"+fbaBox1.getCodePlan()+ ",头程装箱单:" +fbaBox1.getCode() +",纸箱个数"+fbaBox1.getNumBox(),
                            "审核","装箱单",1,fbaBox1.getNid(),fbaBox1.getCode(),fbaBox1.getGuid(),fbaBox1.getCreateTime(),accountList
                    );
                    //资金流水(仓储部-运营公司 纸箱包装费)
                    addAccountDetailedForCompany(operationAccount,warehousingAccount, userInfo,boxProject,
                            "纸箱费，头程计划单:"+fbaBox1.getCodePlan()+ ",头程装箱单:" +fbaBox1.getCode() +",纸箱个数"+fbaBox1.getNumBox(),
                            "审核","装箱单",1,fbaBox1.getNid(),fbaBox1.getCode(),fbaBox1.getGuid(),fbaBox1.getCreateTime(),accountList
                    );
                    if (stringBuffer.length() != 0){
                        stringBuffer.deleteCharAt(stringBuffer.length()-1);
                    }
                    if (transparencyProject != 0.0){
                        //资金流水(运营公司-仓储部 透明计划贴标费用)
                        addAccountDetailedForCompany(warehousingAccount,operationAccount, userInfo,-transparencyProject,
                                "透明计划贴标费用，头程计划单:"+fbaBox1.getCodePlan()+ ",头程装箱单:" +fbaBox1.getCode() +","+stringBuffer,
                                "审核","装箱单",1,fbaBox1.getNid(),fbaBox1.getCode(),fbaBox1.getGuid(),fbaBox1.getCreateTime(),accountList
                        );
                        //资金流水(仓储部-运营公司 透明计划贴标费用)
                        addAccountDetailedForCompany(operationAccount,warehousingAccount, userInfo,transparencyProject,
                                "透明计划贴标费用，头程计划单:"+fbaBox1.getCodePlan()+ ",头程装箱单:" +fbaBox1.getCode() +","+stringBuffer,
                                "审核","装箱单",1,fbaBox1.getNid(),fbaBox1.getCode(),fbaBox1.getGuid(),fbaBox1.getCreateTime(),accountList
                        );
                    }

                }
                try {
//                    businessMapper.insertBatchNew(accountList);
                }catch (Exception e){
                    apiResponse.setMsg("新增账户流水单失败!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }


                if ("自动".equals(fbaBox.getCreationMethod())) {
                    body = new InboundShipmentRequest();

                    //查询网店信息
                    AmazonShop  amazonShop = amazonShopMapper.findAmazonShopByGuid(fbaBox.getSellerId());
                    if (amazonShop != null) {
                        address = new Address();
                        secretsVO = new SellerSecretsVO();
                        getAmazonShop(amazonShop, address, secretsVO);

                        inboundShipmentHeader = new InboundShipmentHeader();
                        inboundShipmentHeader.setShipmentName(fbaBox.getShipmentId() + "-" + fbaBox.getDestinationFulfillmentCenterId());
                        inboundShipmentHeader.setShipFromAddress(address);
                        inboundShipmentHeader.setDestinationFulfillmentCenterId(fbaBox.getDestinationFulfillmentCenterId());
                        if ("0".equals(params.get("num").toString())){
                            inboundShipmentHeader.setShipmentStatus(ShipmentStatus.SHIPPED);
                        } else {
                            inboundShipmentHeader.setShipmentStatus(ShipmentStatus.CANCELLED);
                        }
                        inboundShipmentHeader.setLabelPrepPreference(LabelPrepPreference.SELLER_LABEL);
                        inboundShipmentHeader.setIntendedBoxContentsSource(IntendedBoxContentsSource.FEED);

                        inboundShipmentItems = new InboundShipmentItemList();
                        //查询头程货件详情信息
                        params1 = new HashMap<String, Object>();
                        //头程计划单下所有箱子数据
                        params1.put("codeBox1",fbaBox.getCode());
                        fbaBoxDetailList = fbaBoxDetailMapper.findFbaBoxDetail(params1);

                        if (fbaBoxDetailList.size() == 0){
                            apiResponse.setMsg("头程单名下的商品信息不存在!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }

                        if (fbaBoxDetailList.size() != 0) {
                            //将相同的sku、Asin、FnSku相加起来
                            Set<String> fnSkuList = new HashSet<>();
                            List<FbaBoxDetail> fbaBoxDetailListOld = new ArrayList<>();
                            for (FbaBoxDetail fbaBoxDetail : fbaBoxDetailList){
                                fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetail.getProductInfo(), FbaBoxDetail.class);
                                for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailListNew) {
                                    fnSkuList.add(fbaBoxDetai.getFnsku());
                                    fbaBoxDetailListOld.add(fbaBoxDetai);
                                }
                            }

                            List<FbaBoxDetail> fbaBoxDetailListApi;
                            BigDecimal numPlanDeliver;
                            for (String fnSku : fnSkuList) {
                                fbaBoxDetailListApi = fbaBoxDetailListOld.stream().filter(
                                        fbaBoxDetail1 -> fbaBoxDetail1.getFnsku().equals(fnSku)
                                ).collect(Collectors.toList());
                                numPlanDeliver = BigDecimal.ZERO;
                                for (FbaBoxDetail fbaBoxDetail : fbaBoxDetailListApi){
                                    numPlanDeliver = numPlanDeliver.add(new BigDecimal(fbaBoxDetail.getNumRealityDeliver().equals("")?"0":fbaBoxDetail.getNumRealityDeliver()));
                                }
                                inboundShipmentItem = new InboundShipmentItem();
                                inboundShipmentItem.setSellerSKU(fbaBoxDetailListApi.get(0).getSku());
                                inboundShipmentItem.setFulfillmentNetworkSKU(fbaBoxDetailListApi.get(0).getFnsku());
                                inboundShipmentItem.setQuantityShipped(Integer.valueOf(numPlanDeliver.toString()));
                                inboundShipmentItems.add(inboundShipmentItem);
                            }
                        }

                        body.setInboundShipmentHeader(inboundShipmentHeader);
                        body.setInboundShipmentItems(inboundShipmentItems);
                        body.setMarketplaceId(amazonShop.getMarketplaceIds());
                        api = Helper.buildApi(secretsVO, FbaInboundApi.class);
                        InboundShipmentResponse response = api.updateInboundShipment(body, fbaBox.getShipmentId());
                        apiLogService.addApiLog("api","DeleteOrModify","body：" + body.toString()+","+"response:"+response.getPayload(),"",0, "修改货件updateInboundShipment成功");
                    } else {
                        apiResponse.setMsg(fbaBox.getCode() + "头程单名下的店铺不存在!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                }
            }
            apiResponse.setMsg("审核成功");
            apiResponse.setCode(0);
        } catch (Exception e) {
            if (e.getMessage().equals("Error getting LWA Access Token")) {
                apiResponse.setMsg("获取该网店令牌失败,请核实该店铺是否有权限!");
            }else if (e.getMessage().equals("Bad Request")) {
                apiResponse.setMsg("上传亚马逊货件数据出错,请核实数据再操作!");
            } else {
                if ("0".equals(params.get("num").toString())){
                    apiResponse.setMsg("审核失败!");
                } else {
                    apiResponse.setMsg("拆箱失败!");
                }

            }
            apiLogService.addApiLog("api","DeleteOrModify","body：" + params.get("infoItems").toString(),"",500, apiResponse.getMsg());
            apiResponse.setCode(500);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }

    /**
     * 打印箱标
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse getLabels(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<FbaBox> list;
        Address address;
        SellerSecretsVO secretsVO;
        FbaInboundApi api;
        Map<String, Object> params1;
        List<FbaShipmentDetail> fbaShipmentDetailList;
        String data = "";
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        UserInfo userInfo;
        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaBox.class);
            for (FbaBox fbaBox : list) {
                userInfo= userInfoMapper.findByUserId(params.get("userId").toString());
                if (userInfo == null){
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的用户不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                fbaBox = fbaBoxMapper.queryFirstByGuid(fbaBox.getGuid());
                if (fbaBox == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程装箱单不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }


                //查询网店信息
                AmazonShop  amazonShop = amazonShopMapper.findAmazonShopByGuid(fbaBox.getSellerId());
                if (amazonShop != null) {
                    address = new Address();
                    secretsVO = new SellerSecretsVO();
                    getAmazonShop(amazonShop, address, secretsVO);
                    List<String> packageLabelsToPrint = Arrays.asList("1");
                    api = Helper.buildApi(secretsVO, FbaInboundApi.class);

                    //查询头程货件详情信息
                    params1 = new HashMap<String, Object>();
                    params1.put("code", fbaBox.getCodeShipment());
                    fbaShipmentDetailList = fbaShipmentDetailMapper.queryList(params1);
                    if (fbaShipmentDetailList.size() == 0){
                        apiResponse.setMsg(fbaBox.getCode() + "头程单名下的商品信息不存在!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

                    GetLabelsResponse response =
                            api.getLabels(fbaBox.getShipmentId(),
                                    "PackageLabel_Plain_Paper",
                                    "BARCODE_2D",
                                    null,
                                    packageLabelsToPrint,
                                    null,
                                    fbaBox.getNumBox(), 0);
                    apiLogService.addApiLog("api","Labels","body：" + params.get("infoItems").toString()+","+"response:"+response.getPayload(),"",0, "打印箱标成功!");

                    try {

                        URL url = new URL(response.getPayload().getDownloadURL());
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        // 设置超时间为3秒
                        conn.setConnectTimeout(3 * 1000);
                        // 防止屏蔽程序抓取而返回403错误
                        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

                        // 得到输入流
                        InputStream inputStream = conn.getInputStream();

                        byte[] buffer = new byte[1024];
                        int len = 0;
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        while ((len = inputStream.read(buffer)) != -1) {
                            bos.write(buffer, 0, len);
                        }
                        bos.close();
                        // 获取字节数组
                        byte[] getData = bos.toByteArray();

                        // 文件保存位置
//                        File saveDir = new File(ApiConfig.getUploadPdf());
                        File saveDir = new File(Global.getProfile());
                        if (!saveDir.exists()) {
                            saveDir.mkdir();
                        }
                        String pdfFileName = "/" + fbaBox.getShipmentId() + ".pdf";
                        File file = new File(saveDir + pdfFileName);
                        data = "/profile" + pdfFileName;
                        jsonObject = new JSONObject();
                        jsonObject.put("data",data);
                        jsonArray.add(jsonObject);
                        FileOutputStream fos = new FileOutputStream(file);
                        fos.write(getData);
                        if (fos != null) {
                            fos.close();
                        }
                        if (inputStream != null) {
                            inputStream.close();
                        }
                    } catch (Exception e) {
                        apiResponse.setMsg(fbaBox.getCode() + "文件下载失败!");
                        apiResponse.setCode(400);
                        return apiResponse;
                    }
                } else {
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的店铺不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                fbaBox.setBoxMarkUser(userInfo.getUserName());
                fbaBox.setBoxMarkTime(new Date());
                fbaBox.setStatePrint("5");
                fbaBox.setStatePrintName("箱标已打印");
                fbaBoxMapper.updateByGuid(fbaBox);
            }
            apiResponse.setMsg("打印箱标成功!");
            apiResponse.setData(jsonArray);
            apiResponse.setCode(0);
        }catch (Exception e) {
            if (e.getMessage().equals("Error getting LWA Access Token")) {
                apiResponse.setMsg("获取该网店令牌失败,请核实该店铺是否有权限!");
            }else if (e.getMessage().equals("Bad Request")) {
                apiResponse.setMsg("上传亚马逊货件数据出错,请核实数据再操作!");
            } else {
                apiResponse.setMsg("打印箱标失败!");
            }
            apiLogService.addApiLog("api","Labels","body：" + params.get("infoItems").toString(),"",500, apiResponse.getMsg());
            apiResponse.setCode(500);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }

    /**
     * 打印箱标尾程
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse getLabelsWc(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<HwTailprogramApi> list;
        Address address;
        SellerSecretsVO secretsVO;
        FbaInboundApi api;
        Map<String, Object> params1;
        List<FbaShipmentDetail> fbaShipmentDetailList;
        String data = "";
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        FbaBox fbaBox;
        HwTailprogramApi hwTailprogramApi1;
        Map<String, Object> paramHw = new HashMap<String, Object>();
        try {
            list = JSON.parseArray(params.get("infoItems").toString(), HwTailprogramApi.class);
            for (HwTailprogramApi hwTailprogramApi : list) {
                paramHw.put("moduleTable", "HW_TailProgram");
                paramHw.put("entity", new HwTailprogramApi());
                paramHw.put("codeBox", hwTailprogramApi.getCodebox());
                hwTailprogramApi1 = hwTailprogramMapper.queryFirstRecord1(paramHw);
                if (hwTailprogramApi1.getStatePrintName().equals(TailprogramEnum.StateName.PRINTNOHAVE.value)) {
                    apiResponse.setMsg(hwTailprogramApi1.getCodebox() + "商品标未打印,核实后再操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                if (hwTailprogramApi1.getIsfmb() != null){
                    if (hwTailprogramApi1.getIsfmb() != 0){
                        if (!hwTailprogramApi1.getStatePrintName().equals(TailprogramEnum.StateName.PRINTTWO.value)) {
                            apiResponse.setMsg(hwTailprogramApi1.getCodebox() + "透明标未打印,核实后再操作!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                    }
                }
                fbaBox = fbaBoxMapper.queryFirstByCode(hwTailprogramApi1.getCodebox());
                if (fbaBox == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程装箱单不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }


                //查询网店信息
                AmazonShop  amazonShop = amazonShopMapper.findAmazonShopByGuid(fbaBox.getSellerId());
                if (amazonShop != null) {
                    address = new Address();
                    secretsVO = new SellerSecretsVO();
                    getAmazonShop(amazonShop, address, secretsVO);
                    List<String> packageLabelsToPrint = Arrays.asList("1");
                    api = Helper.buildApi(secretsVO, FbaInboundApi.class);

                    //查询头程货件详情信息
                    params1 = new HashMap<String, Object>();
                    params1.put("code", fbaBox.getCodeShipment());
                    fbaShipmentDetailList = fbaShipmentDetailMapper.queryList(params1);
                    if (fbaShipmentDetailList.size() == 0){
                        apiResponse.setMsg(fbaBox.getCode() + "头程单名下的商品信息不存在!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

                    GetLabelsResponse response =
                            api.getLabels(fbaBox.getShipmentId(),
                                    "PackageLabel_Plain_Paper",
                                    "BARCODE_2D",
                                    null,
                                    packageLabelsToPrint,
                                    null,
                                    fbaBox.getNumBox(), 0);
                    apiLogService.addApiLog("api","Labels","body：" + params.get("infoItems").toString()+","+"response:"+response.getPayload(),"",0, "打印箱标成功!");

                    try {

                        URL url = new URL(response.getPayload().getDownloadURL());
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        // 设置超时间为3秒
                        conn.setConnectTimeout(3 * 1000);
                        // 防止屏蔽程序抓取而返回403错误
                        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

                        // 得到输入流
                        InputStream inputStream = conn.getInputStream();

                        byte[] buffer = new byte[1024];
                        int len = 0;
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        while ((len = inputStream.read(buffer)) != -1) {
                            bos.write(buffer, 0, len);
                        }
                        bos.close();
                        // 获取字节数组
                        byte[] getData = bos.toByteArray();

                        // 文件保存位置
                        File saveDir = new File(Global.getProfile());
                        if (!saveDir.exists()) {
                            saveDir.mkdir();
                        }
                        String pdfFileName = "/" + fbaBox.getShipmentId() + ".pdf";
                        File file = new File(saveDir + pdfFileName);
                        data = "/profile" + pdfFileName;
                        jsonObject = new JSONObject();
                        jsonObject.put("data",data);
                        jsonArray.add(jsonObject);
                        FileOutputStream fos = new FileOutputStream(file);
                        fos.write(getData);
                        if (fos != null) {
                            fos.close();
                        }
                        if (inputStream != null) {
                            inputStream.close();
                        }
                    } catch (Exception e) {
                        apiResponse.setMsg(fbaBox.getCode() + "文件下载失败!");
                        apiResponse.setCode(400);
                        return apiResponse;
                    }
                } else {
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的店铺不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                if (hwTailprogramApi1.getStatePrintName().equals(TailprogramEnum.StateName.PRINTONE.value)){
                    hwTailprogramApi1.setStatePrintName(TailprogramEnum.StateName.PRINTFOUR.value);
                }
                if (hwTailprogramApi1.getStatePrintName().equals(TailprogramEnum.StateName.PRINTTWO.value)){
                    hwTailprogramApi1.setStatePrintName(TailprogramEnum.StateName.PRINTTHREE.value);
                }
                hwTailprogramMapper.update(hwTailprogramApi1);
            }
            apiResponse.setMsg("外箱标打印!");
            apiResponse.setData(jsonArray);
            apiResponse.setCode(0);
        }catch (ApiException e) {
            if (e.getMessage().equals("Error getting LWA Access Token")) {
                apiResponse.setMsg("获取该网店令牌失败,请核实该店铺是否有权限!");
            }else if (e.getMessage().equals("Bad Request")) {
                apiResponse.setMsg(e.getResponseBody());
            } else {
                apiResponse.setMsg("打印箱标失败!");
            }
            apiResponse.setCode(500);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }

    /**
     * 导入FBA
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse fbaImport(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<FbaBox> list;
        Address address;
        SellerSecretsVO secretsVO;
        FbaInboundApi api;
        Map<String, Object> params1;
        UserInfo userInfo;
        List<FbaBoxDetail> fbaBoxDetails;
        File file;
        FileInputStream input;
        HSSFWorkbook workbook;
        HSSFSheet sheet;
        HSSFRow row;
        HSSFCell cell = null;
        FbaBoxDetail fbaBoxDetailNew;
        FileOutputStream out;
        FeedsApi feedsApi;
        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaBox.class);
            for (FbaBox fbaBox : list) {

                userInfo= userInfoMapper.findByUserId(fbaBox.getaUser());
                if (userInfo == null){
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的用户不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                fbaBox = fbaBoxMapper.queryFirstByGuid(fbaBox.getGuid());
                if (fbaBox == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程装箱单不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                //查询是否有重复的fba导入
                List<FbaBox> fbaBoxList = fbaBoxMapper.queryFirstByShipmentId(params.get("remark").toString());
                if (fbaBoxList.size() != 0) {
                    for (FbaBox fbaBox1: fbaBoxList){
                        if (!fbaBox1.getGuid().equals(fbaBox.getGuid())){
                            apiResponse.setMsg(params.get("remark").toString()+"该FBA编号已导入,请核实后再操作!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                    }
                }

                //查询网店信息
                AmazonShop  amazonShop = amazonShopMapper.findAmazonShopByGuid(fbaBox.getSellerId());
                if (amazonShop != null) {
                    address = new Address();
                    secretsVO = new SellerSecretsVO();
                    getAmazonShop(amazonShop, address, secretsVO);
                    api = Helper.buildApi(secretsVO, FbaInboundApi.class);


                    if (fbaBox.getCreationMethod().equals("手动")) {
                        //查询详情信息
                        params1 = new HashMap<String, Object>();
                        params1.put("codeBox1", fbaBox.getCode());
                        List<FbaBoxDetail> fbaBoxDetailList = fbaBoxDetailMapper.findFbaBoxDetail(params1);
                        if (fbaBoxDetailList.size() == 0) {
                            apiResponse.setMsg(fbaBox.getCode() + "头程单名下的商品信息不存在!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                        fbaBoxDetailList = JSON.parseArray(fbaBoxDetailList.get(0).getProductInfo(), FbaBoxDetail.class);

                        GetShipmentItemsResponse response = api.getShipmentItemsByShipmentId(params.get("remark").toString(), amazonShop.getSellerId());
                        apiLogService.addApiLog("api", "FBAIMPORT", "fba：" + params.get("remark").toString() + "," + "sellerId：" + amazonShop.getSellerId() + "," + "response:" + response.getPayload(), "", 0, "getShipmentItemsByShipmentId查询成功");
                        //去重亚马逊条数
                        Set<String> setItem = new HashSet<>();

                        GetShipmentItemsResult payload = response.getPayload();
                        for (InboundShipmentItem itemData : payload.getItemData()) {
                            setItem.add(itemData.getSellerSKU());
                        }

                        //去重erp商品条数
                        Set<String> setErp = new HashSet<>();
                        for (FbaBoxDetail fbaBoxDetail : fbaBoxDetailList) {
                            setErp.add(fbaBoxDetail.getSku());
                        }

                        boolean comarry = comarry(setErp, setItem);
                        if (!comarry) {
                            apiResponse.setMsg("FBA导入失败," + "商品信息不匹配!");
                            apiResponse.setCode(500);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }


                        List<String> shipmentIdList = new ArrayList<>();
                        shipmentIdList.add(params.get("remark").toString());
                        GetShipmentsResponse getShipmentsResponse = api.getShipments("SHIPMENT", amazonShop.getSellerId(), null, shipmentIdList, null, null, null);
                        apiLogService.addApiLog("api", "FBAIMPORT", "fba：" + params.get("remark").toString() + "," + "sellerId：" + amazonShop.getSellerId() + "," + "response:" + response.getPayload(), "", 0, "getShipments查询成功");
                        GetShipmentsResult payload1 = getShipmentsResponse.getPayload();
                        for (InboundShipmentInfo inboundShipmentInfo : payload1.getShipmentData()) {
                            try {
                                //查询物流方式仓库梯度信息
                                Map<String, Object> params11 = new HashMap<String, Object>();
                                params11.put("logisticsMmodeGuid",fbaBox.getLogisticsMmodeGuid());
                                List<LogisticsMmodeCk> logisticsMmodeCkList = logsticsMmodeCkMapper.findLogisticsMmodeCk(params11);
                                List<LogisticsMmodeCk> logisticsMmodeCkS = new ArrayList<>();
                                if (logisticsMmodeCkList.size() != 0){
                                    logisticsMmodeCkS  = logisticsMmodeCkList.stream().filter(logisticsMmodeCk ->
                                            inboundShipmentInfo.getDestinationFulfillmentCenterId().equals(logisticsMmodeCk.getWarehouseName())).collect(Collectors.toList());
                                }

                                if (logisticsMmodeCkS.size() != 0){
                                    fbaBox.setWarehouseSurchargePrice(logisticsMmodeCkS.get(0).getWarehouseCost());
                                }else {
                                    fbaBox.setWarehouseSurchargePrice(BigDecimal.ZERO);
                                }
                                BigDecimal warehouseSurcharge = (fbaBox.getWeightCal().multiply(fbaBox.getWarehouseSurchargePrice())).setScale(2, BigDecimal.ROUND_HALF_UP);
                                fbaBox.setWarehouseSurcharge(warehouseSurcharge);
                                fbaBox.setPriceTranCalWeightPredict(fbaBox.getPriceTranCalWeightPredict().add(warehouseSurcharge));
                                fbaBox.setActualLogisticsFreight(fbaBox.getActualLogisticsFreight().add(warehouseSurcharge));
                                if (fbaBox.getLoadDelivery().equals("是")){
                                    //抛发计重：【=MAX（装箱抛重，单票起重）约分】
                                    BigDecimal weightCalPf = precision(fbaBox.getSinglePassCrane().max(fbaBox.getWeightVol()));
                                    BigDecimal warehouseSurchargepf = (weightCalPf.multiply(fbaBox.getWarehouseSurchargePrice())).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    fbaBox.setPriceTranCalWeightPredictPf(fbaBox.getPriceTranCalWeightPredictPf().add(warehouseSurchargepf));
                                    fbaBox.setActualLogisticsFreightPf(fbaBox.getActualLogisticsFreightPf().add(warehouseSurchargepf));
                                    fbaBox.setWarehouseSurchargePf(warehouseSurchargepf);
                                }

                                //修改导入fba
                                fbaBox.setState("3");
                                fbaBox.setStateName("FBA已导入");
                                fbaBox.setShipmentId(inboundShipmentInfo.getShipmentId());
                                fbaBox.setDestinationFulfillmentCenterId(inboundShipmentInfo.getDestinationFulfillmentCenterId());
                                fbaBox.setTrackingCode(params.get("trackingCode").toString());
                                fbaBoxMapper.updateByGuid(fbaBox);
                            } catch (Exception e) {
                                apiResponse.setMsg(fbaBox.getCode() + "修改头程装箱单失败!");
                                apiResponse.setCode(400);
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }

                        }
                    } else {
                        //查询详情数据
                        params1 = new HashMap<String, Object>();
                        params1.put("codeShipment", fbaBox.getCodeShipment());
                        params1.put("num", "1");
                        fbaBoxDetails = fbaBoxDetailService.queryAutoList(params1);
                        if (fbaBoxDetails.size() == 0) {
                            apiResponse.setMsg(fbaBox.getCode() + "头程单名下的店铺不存在!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }

                        try {
                            //根据数据生成表格
                            if (amazonShop.getRegionName().equals("欧洲")){
                                file = new File(ApiConfig.getUploadExcel() + "/poitest1.xlsx");
                            } else {
                                file = new File(ApiConfig.getUploadExcel() + "/poitest2.xlsx");
                            }
                            input = new FileInputStream(file);
                            // HSSFWorkbook用于操作后缀为.xls的excel表格，XSSFWorkbook用于操作.xlsx的excel表格
                            workbook = new HSSFWorkbook(input);
                            // 获取工作簿的方法有两种，一种是根据索引获取，第一个sheet的索引为0，还有一种是根据sheet名称获取
                            sheet = workbook.getSheetAt(0);
                            // 最后一行行号等于sheet的数据行数
                            for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
                                // 得到每一行
                                row = sheet.getRow(i);
                                //排除空白行
                                if (row == null && i == 2) {
                                    continue;
                                }
                                if (i == 0) {
                                    cell = row.getCell(1);
                                    cell.setCellValue(fbaBox.getShipmentId());
                                } else if (i == 3) {
                                    for (int j = 0; j < fbaBox.getNumBox(); j++) {
                                        cell = row.createCell(10 + j);
                                        cell.setCellValue("Box " + (j + 1) + " - QTY");
                                    }
                                } else if (fbaBoxDetails.size() > 0 && i > 3 && i < 62) {
                                    for (int k = 0; k < fbaBoxDetails.size() - 4; k++) {
                                        fbaBoxDetailNew = fbaBoxDetails.get(k);
                                        if (i == 4 + k) {
                                            cell = row.createCell(0);
                                            cell.setCellValue(fbaBoxDetailNew.getSku());
                                            cell = row.createCell(3);
                                            cell.setCellValue(fbaBoxDetailNew.getFnsku());
                                            cell = row.createCell(8);
                                            cell.setCellValue(new Double(fbaBoxDetailNew.getNumPlanDeliver()));
                                            cell = row.createCell(9);
                                            cell.setCellValue(new Double(fbaBoxDetailNew.getNumPlanDeliver()));

                                            addBox(fbaBoxDetailNew, cell, row,amazonShop);
                                        }
                                    }
                                } else if (i == 62) {
                                    for (int j = 0; j < fbaBox.getNumBox(); j++) {
                                        cell = row.createCell(10 + j);
                                        cell.setCellValue("Box " + (j + 1));
                                    }
                                } else if (i == 63) {
                                    fbaBoxDetailNew = fbaBoxDetails.get(fbaBoxDetails.size() - 4);
                                    addBox(fbaBoxDetailNew, cell, row,amazonShop);
                                } else if (i == 64) {
                                    fbaBoxDetailNew = fbaBoxDetails.get(fbaBoxDetails.size() - 3);
                                    addBox(fbaBoxDetailNew, cell, row,amazonShop);
                                } else if (i == 65) {
                                    fbaBoxDetailNew = fbaBoxDetails.get(fbaBoxDetails.size() - 2);
                                    addBox(fbaBoxDetailNew, cell, row,amazonShop);
                                } else if (i == 66) {
                                    fbaBoxDetailNew = fbaBoxDetails.get(fbaBoxDetails.size() - 1);
                                    addBox(fbaBoxDetailNew, cell, row,amazonShop);
                                }
                            }
                            sheet.shiftRows(61, 67, -(67 - 10 - (fbaBoxDetails.size() - 4)));
                            out = new FileOutputStream(ApiConfig.getUploadExcel() + "/" + fbaBox.getShipmentId() + ".xlsx");
                            workbook.write(out);
                            out.close();
                            // 关闭资源
                            workbook.close();
                        } catch (Exception e) {
                            apiResponse.setMsg(fbaBox.getCode() + "生成Excel表格失败!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                        //上传箱子数据putTransportDetails
                        NonPartneredSmallParcelPackageInputList nonPartneredSmallParcelPackageInputs;
                        NonPartneredSmallParcelDataInput nonPartneredSmallParcelDataInput;
                        NonPartneredSmallParcelPackageInput nonPartneredSmallParcelPackageInput;
                        TransportDetailInput transportDetailInput;
                        PutTransportDetailsRequest body;
                        PutTransportDetailsResponse response;

                        nonPartneredSmallParcelPackageInputs = new NonPartneredSmallParcelPackageInputList();
                        nonPartneredSmallParcelDataInput = new NonPartneredSmallParcelDataInput();
                        nonPartneredSmallParcelDataInput.setCarrierName("other");
                        nonPartneredSmallParcelDataInput.setPackageList(nonPartneredSmallParcelPackageInputs);
                        for (int i = 0; i < fbaBoxDetails.size(); i++) {
                            nonPartneredSmallParcelPackageInput = new NonPartneredSmallParcelPackageInput();
                            nonPartneredSmallParcelPackageInput.setTrackingId(" ");
                            nonPartneredSmallParcelPackageInputs.add(nonPartneredSmallParcelPackageInput);
                        }
                        transportDetailInput = new TransportDetailInput();
                        transportDetailInput.setNonPartneredSmallParcelData(nonPartneredSmallParcelDataInput);

                        body = new PutTransportDetailsRequest();
                        body.setIsPartnered(false);
                        body.setShipmentType(ShipmentType.SP);
                        body.setTransportDetails(transportDetailInput);

                        api = Helper.buildApi(secretsVO, FbaInboundApi.class);
                        response = api.putTransportDetails(fbaBox.getShipmentId(), body);
                        apiLogService.addApiLog("api", "CancelParcel", "body：" + body.toString() + "," + "response:" + response.getPayload(), "", 0, "更新物流信息putTransportDetails成功!");
                        if (response.getErrors() == null) {
                            String contentType = "application/vnd.ms-excel";
                            CreateFeedDocumentSpecification createFeedDocumentSpecification = new CreateFeedDocumentSpecification();
                            createFeedDocumentSpecification.setContentType(contentType);
                            feedsApi = Helper.buildApi(secretsVO, FeedsApi.class);
                            CreateFeedDocumentResponse createFeedDocumentResponse = feedsApi.createFeedDocument(createFeedDocumentSpecification);
                            String feedDocumentId = createFeedDocumentResponse.getFeedDocumentId();
                            String url = createFeedDocumentResponse.getUrl();

                            String filePath = ApiConfig.getUploadExcel() + "/" + fbaBox.getShipmentId() + ".xlsx";
                            byte[] source = null;
                            try {
                                source = Files.readAllBytes(Paths.get(filePath));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            if (source == null) {
                                apiResponse.setMsg("文件读取错误");
                                apiResponse.setCode(400);
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }
                            upload(source, url, contentType, 0, fbaBox,fbaBoxDetails);
                            CreateFeedSpecification createFeedSpecification = new CreateFeedSpecification();
                            createFeedSpecification.setFeedType("POST_FLAT_FILE_FROM_EXCEL_FBA_CREATE_CARTON_INFO");
                            createFeedSpecification.setMarketplaceIds(Collections.singletonList(amazonShop.getMarketplaceIds()));
                            createFeedSpecification.setInputFeedDocumentId(feedDocumentId);
                            CreateFeedResponse createFeedResponse = feedsApi.createFeed(createFeedSpecification);
                            String feedId = createFeedResponse.getFeedId();
                            Feed feed;
                            while (true) {
                                feed = feedsApi.getFeed(feedId);
                                if (feed.getProcessingStatus() != Feed.ProcessingStatusEnum.DONE) {
                                    try {
                                        TimeUnit.SECONDS.sleep(2);
                                    } catch (InterruptedException ignored) {
                                        apiResponse.setMsg("访问feed失败!");
                                        apiResponse.setCode(400);
                                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                    }
                                } else {
                                    break;
                                }
                            }
                            String resultFeedDocumentId = feed.getResultFeedDocumentId();
                            FeedDocument feedDocument = feedsApi.getFeedDocument(resultFeedDocumentId);
                            System.out.println(feedDocument);
                            Boolean upload = upload(source, feedDocument.getUrl(), contentType, 1, fbaBox,fbaBoxDetails);
                            Path path2 = Paths.get(filePath);
                            Files.delete(path2);
                            if (upload == false) {
                                apiResponse.setCode(500);
                                apiResponse.setMsg("FBA导入失败,原因是上传箱子数据异常!");
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }
                        }
                        try {
                            //修改导入fba
                            fbaBox.setState("3");
                            fbaBox.setStateName("FBA已导入");
                            fbaBox.setTrackingCode(params.get("trackingCode").toString());
                            fbaBoxMapper.updateByGuid(fbaBox);
                        } catch (Exception e) {
                            apiResponse.setMsg(fbaBox.getCode() + "修改头程装箱单失败!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                    }
                } else {
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的店铺不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
            }
            apiResponse.setMsg("FBA导入成功!");
            apiResponse.setCode(0);
        }catch (Exception e) {
            if (e.getMessage().equals("Error getting LWA Access Token")) {
                apiResponse.setMsg("获取该网店令牌失败,请核实该店铺是否有权限!");
            }else if (e.getMessage().equals("Bad Request")) {
                apiResponse.setMsg("上传亚马逊货件数据出错,请核实数据再操作!");
            } else {
                apiResponse.setMsg("导入FBA失败!");
            }
            apiLogService.addApiLog("api","Labels","body：" + params.get("infoItems").toString(),"",500, apiResponse.getMsg());
            apiResponse.setCode(500);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }


    /**
     * 判断两个数组是否相同
     * @param arr
     * @param arr2
     * @return
     */
    public static boolean comarry(Set<String> arr,Set<String> arr2) {
        //首先比较两个数组长度，如果长度不相同，数组内容肯定不相同，返回false
        if (arr.size() != arr2.size()) {
            return false;
        }
        if (arr.containsAll(arr2)){
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void openPdf(Map<String, Object> params, HttpServletResponse response)  {
        try {
            File file = new File(ApiConfig.getUploadPdf()+"/"+params.get("params").toString()+".pdf");
            FileInputStream fileInputStream = new FileInputStream(file);
            response.setHeader("Content-Type", "application/pdf");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 头程装箱并发货回退
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse rollbackState(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<FbaBox> list;
        Map<String, Object> params1;
        UserInfo userInfo;
        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaBox.class);

            for (FbaBox fbaBox : list) {
                userInfo = userInfoMapper.findByUserId(fbaBox.getaUser());
                if (userInfo == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的用户不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                FbaBox fbaBox1 = fbaBoxMapper.queryFirstByGuid(fbaBox.getGuid());
                if (fbaBox1 == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程单不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                if(!fbaBox1.getStatePrint().equals("0") &&! fbaBox1.getStatePrint().equals("1")){
                    apiResponse.setMsg("选择单据已打印商品标,不允许回退!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                //删除装箱单、详情、货件、回退头程计划单
                fbaBoxMapper.deleteGuid(fbaBox1);

                //删除装箱单详情
                fbaBoxDetailMapper.deleteCodeBox(fbaBox1.getCode());

                if ("手动".equals(fbaBox.getCreationMethod())) {

                    //删除货件
                    fbaShipmentMapper.deleteCode(fbaBox1.getCodeShipment());

                    //删除货件详情
                    fbaShipmentDetailMapper.deleteCodeShipmentOrder(fbaBox1.getCodeShipment());

                    //修改头程计划单状态
                    fbaPlanOrderMapper.updateCode(fbaBox1.getCodePlan());
                } else {
                    //自动(修改货件的状态)
                    FbaShipment fbaShipment = fbaShipmentMapper.queryFirstByCode(fbaBox1.getCodeShipment());
                    fbaShipment.setState("0");
                    fbaShipmentMapper.updateByCode(fbaShipment);
                }
            }
            apiResponse.setMsg("回退成功");
            apiResponse.setCode(0);
        } catch (Exception e) {
            if (e.getMessage().equals("Error getting LWA Access Token")) {
                apiResponse.setMsg("获取该网店令牌失败,请核实该店铺是否有权限!");
            }else if (e.getMessage().equals("Bad Request")) {
                apiResponse.setMsg("上传亚马逊货件数据出错,请核实数据再操作!");
            } else {
                apiResponse.setMsg("回退失败!");
                apiResponse.setCode(400);
            }
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }

    /**
     * 强制回退
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse forcedRollback(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<FbaBox> list;
        Map<String, Object> params1;
        UserInfo userInfo;
        AccountCountForCompany logisticsAccount;
        AccountCountForCompany operationAccount;
        AccountCountForCompany warehousingAccount;
        Double transparencyProject;
        Double boxProject = 0.0;
        Double priceTranPredict1 = 0.0;
        SysAccountBandDept sysAccountBandDept;
        List<AccountDetailedForCompany> accountList;
        StringBuffer stringBuffer = null;
        List<FbaBoxDetail> fbaBoxDetailList;
        List<FbaBoxDetail> fbaBoxDetailListNew = null;
        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaBox.class);

            for (FbaBox fbaBox : list) {
                accountList =new ArrayList<>();
                userInfo = userInfoMapper.findByUserId(fbaBox.getaUser());
                if (userInfo == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的用户不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                FbaBox fbaBox1 = fbaBoxMapper.queryFirstByGuid(fbaBox.getGuid());
                if (fbaBox1 == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程单不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                if (fbaBox1.getCreationMethod().equals("手动")) {
                    apiResponse.setMsg("创建方式只允许是自动下,请核实后在操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                if (fbaBox1.getIsTracking().equals("是")) {
                    apiResponse.setMsg("亚马逊货件状态已发货,不允许强制回退!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                if (fbaBox1.getState().equals("1")) {
                    operationAccount = accountCountForCompanyMapper.queryFirstByVGsBm(fbaBox1.getCodeCompany());
                    if (operationAccount == null) {
                        apiResponse.setMsg("运营公司实时资金不存在,请核实后再操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

                    //查询仓储部绑定账户
                    sysAccountBandDept = sysAccountBandDeptMapper.findByAccountId("CCB");
                    if (sysAccountBandDept == null) {
                        apiResponse.setMsg("仓储部绑定账户未启用或不存在,请核实后再操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    // 仓储部绑定账户增加物流费用
                    warehousingAccount = accountCountForCompanyMapper.queryFirstByVGsBm(sysAccountBandDept.getvGsBm());
                    if (warehousingAccount == null) {
                        apiResponse.setMsg("仓储部实时资金不存在,请核实后再操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

                    //查询头程货件详情信息
                    params1 = new HashMap<String, Object>();
                    //头程计划单下所有箱子数据
                    params1.put("codeBox1", fbaBox.getCode());
                    fbaBoxDetailList = fbaBoxDetailMapper.findFbaBoxDetail(params1);

                    if (fbaBoxDetailList.size() == 0) {
                        apiResponse.setMsg("头程单名下的商品信息不存在!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

                    //计算装箱物料费 + 透明计划贴标费
                    boxProject = Double.valueOf(fbaBox1.getNumBox()) * 15;

                    transparencyProject = 0.0;
                    Map<Integer, Integer> numBiDc;
                    numBiDc = new HashMap<>();
                    if (fbaBoxDetailList.size() != 0) {
                        for (int i = 0; i < fbaBoxDetailList.size(); i++) {
                            fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(i).getProductInfo(), FbaBoxDetail.class);
                            for (int j = 0; j < fbaBoxDetailListNew.size(); j++) {
                                if (numBiDc.get(j) == null) {
                                    numBiDc.put(j, new Integer(fbaBoxDetailListNew.get(j).getNumRealityDeliver().equals("") ? "0" : fbaBoxDetailListNew.get(j).getNumRealityDeliver()));
                                } else {
                                    numBiDc.put(j, numBiDc.get(j) + (new Integer(fbaBoxDetailListNew.get(j).getNumRealityDeliver().equals("") ? "0" : fbaBoxDetailListNew.get(j).getNumRealityDeliver())));
                                }
                            }
                        }
                        fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(0).getProductInfo(), FbaBoxDetail.class);
                        stringBuffer = new StringBuffer();
                        for (int j = 0; j < fbaBoxDetailListNew.size(); j++) {
                            //修改库存总数量
                            updateNum(fbaBox1, fbaBoxDetailListNew.get(j), apiResponse, userInfo, 1, numBiDc.get(j));
                            if (apiResponse.getCode() == 400) {
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return apiResponse;
                            }
                            if (!fbaBoxDetailListNew.get(j).getvDFilesDefault().equals("无附件")) {
                                //详情备注赋值
                                stringBuffer.append(fbaBoxDetailListNew.get(j).getCommodityCode() + ",数量" + numBiDc.get(j) + "个,");
                                //累加透明计划贴标费
                                transparencyProject = transparencyProject + (Double.valueOf(numBiDc.get(j)) * (0.6));
                            }
                            for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailList) {
                                fbaBoxDetai.setTrackingCode(null);
                                fbaBoxDetailMapper.updateByGuid(fbaBoxDetai);
                            }
                        }
                    }
                    if (fbaBox1.getIsDeliver() == 1) {
                        //头程冻结的实际物流费用
                        priceTranPredict1 = Double.valueOf(fbaBox1.getActualLogisticsFreight().toString());

//                    查询物流部账号
                        sysAccountBandDept = sysAccountBandDeptMapper.findByAccountId("WLB");
                        if (sysAccountBandDept == null) {
                            apiResponse.setMsg("物流部门绑定账户未启用或不存在,请核实后再操作!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }

                        // 物流公司增加物流费用
                        logisticsAccount = accountCountForCompanyMapper.queryFirstByVGsBm(sysAccountBandDept.getvGsBm());
                        if (logisticsAccount == null) {
                            apiResponse.setMsg("物流公司实时资金不存在,请核实后再操作!");
                            apiResponse.setCode(400);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }

//                    资金流水(物流部 - 运营公司 头程物流费)
                        addAccountDetailedForCompany(operationAccount, logisticsAccount, userInfo, -priceTranPredict1,
                                "(回退)头程物流费，头程计划单:" + fbaBox1.getCodePlan() + "," + fbaBox1.getShipmentId() + "," + fbaBox1.getNameLogsticsWay(),
                                "物流服务→头程运费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                        );
                        //物流部减少头程物流费
                        logisticsAccount.setfJe(logisticsAccount.getfJe() - priceTranPredict1);
                        accountCountForCompanyMapper.updateAccountCountForCompany(logisticsAccount);
                        //资金流水(运营公司 - 物流部 头程物流费)
                        addAccountDetailedForCompany(logisticsAccount, operationAccount, userInfo, priceTranPredict1,
                                "(回退)头程物流费，头程计划单:" + fbaBox1.getCodePlan() + "," + fbaBox1.getShipmentId() + "," + fbaBox1.getNameLogsticsWay(),
                                "物流服务→头程运费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                        );
                        //运营公司增加头程物流费
                        operationAccount.setfJe(operationAccount.getfJe() + priceTranPredict1);

                        //资金流水(仓储部 - 运营公司 纸箱包装费)
                        addAccountDetailedForCompany(operationAccount, warehousingAccount, userInfo, -boxProject,
                                "(回退)纸箱费，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + ",纸箱个数" + fbaBox1.getNumBox(),
                                "仓储服务→纸箱费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                        );
                        //仓储部减少纸箱包装费
                        warehousingAccount.setfJe(warehousingAccount.getfJe() - boxProject);
                        //资金流水(运营公司 - 仓储部 纸箱包装费)
                        addAccountDetailedForCompany(warehousingAccount, operationAccount, userInfo, boxProject,
                                "(回退)纸箱费，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + ",纸箱个数" + fbaBox1.getNumBox(),
                                "仓储服务→纸箱费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                        );
                        //运营公司增加纸箱包装费
                        operationAccount.setfJe(operationAccount.getfJe() + boxProject);

                        if (stringBuffer.length() != 0) {
                            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                        }
                        if (transparencyProject != 0.0) {
                            //资金流水(仓储部-运营公司 透明计划贴标费用)
                            addAccountDetailedForCompany(operationAccount, warehousingAccount, userInfo, -transparencyProject,
                                    "(回退)透明计划贴标费用，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + ","  + stringBuffer,
                                    "仓储服务→透明计划贴标费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                            );
                            //仓储部减少 透明计划贴标费用
                            warehousingAccount.setfJe(warehousingAccount.getfJe() - transparencyProject);

                            //资金流水(运营公司-仓储部 透明计划贴标费用)
                            addAccountDetailedForCompany(warehousingAccount, operationAccount, userInfo, transparencyProject,
                                    "(回退)透明计划贴标费用，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + "," + stringBuffer,
                                    "仓储服务→透明计划贴标费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                            );
                            //运营公司增加 透明计划贴标费用
                            operationAccount.setfJe(operationAccount.getfJe() + transparencyProject);
                        }
                        //更新仓储部
                        accountCountForCompanyMapper.updateAccountCountForCompany(warehousingAccount);

                        //更新运营公司
                        accountCountForCompanyMapper.updateAccountCountForCompany(operationAccount);
                    }
                }
                //海外仓逻辑
                if (fbaBox1.getIsDeliver() == 1){
                    delHwTailprogram(apiResponse,fbaBox1);
                    if (apiResponse.getCode() == 400){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                }
                try {
                    businessMapper.insertBatchNew(accountList);
                }catch (Exception e){
                    apiResponse.setMsg("新增账户流水单失败!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                //删除装箱单、详情、货件、回退头程计划单
                fbaBoxMapper.deleteGuid(fbaBox1);

                //删除装箱单详情
                fbaBoxDetailMapper.deleteCodeBox(fbaBox1.getCode());

                //删除货件
                fbaShipmentMapper.deleteCode(fbaBox1.getCodeShipment());

                //删除货件详情
                fbaShipmentDetailMapper.deleteCodeShipmentOrder(fbaBox1.getCodeShipment());

                //修改头程计划单状态
                fbaPlanOrderMapper.updateCode(fbaBox1.getCodePlan());

                //删除拼票数据
                if (!fbaBox1.getStateTrack().equals("0")){
                    FbaSpellTicket fbaSpellTicket = new FbaSpellTicket();
                    fbaSpellTicket.setCode(fbaBox1.getCode());
                    fbaSpellTickMapper.deleteCode(fbaSpellTicket);

                    fbaSpellTicketDetailMapper.delete(fbaBox1.getCode());
                }
            }
            apiResponse.setMsg("强制回退成功");
            apiResponse.setCode(0);
        } catch (Exception e) {
            if (e.getMessage().equals("Error getting LWA Access Token")) {
                apiResponse.setMsg("获取该网店令牌失败,请核实该店铺是否有权限!");
            }else if (e.getMessage().equals("Bad Request")) {
                apiResponse.setMsg("上传亚马逊货件数据出错,请核实数据再操作!");
            } else {
                apiResponse.setMsg("强制回退失败!");
                apiResponse.setCode(400);
            }
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }

    /**
     * 头程完成单回退
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse completeBackoff(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<FbaBox> list;
        UserInfo userInfo;
        List<FbaBoxDetail> fbaBoxDetailListNew = null;
        Map<String, Object> params1;
        List<FbaBoxDetail> fbaBoxDetailList;
        AccountCountForCompany logisticsAccount;
        AccountCountForCompany operationAccount;
        AccountCountForCompany warehousingAccount;
        Double transparencyProject;
        Double boxProject = 0.0;
        Double priceTranPredict1 = 0.0;
        SysAccountBandDept sysAccountBandDept;
        List<AccountDetailedForCompany> accountList = null;
        StringBuffer stringBuffer = null;

        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaBox.class);

            for (FbaBox fbaBox : list) {
                accountList =new ArrayList<>();
                userInfo = userInfoMapper.findByUserId(fbaBox.getaUser());
                if (userInfo == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的用户不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                FbaBox fbaBox1 = fbaBoxMapper.queryFirstByGuid(fbaBox.getGuid());
                if (fbaBox1 == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程单不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                if (!fbaBox1.getState().equals("1")) {
                    apiResponse.setMsg(fbaBox.getCode() + "状态不是已完成,不允许回退!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                if (!fbaBox1.getStateTrack().equals("0")) {
                    apiResponse.setMsg(fbaBox.getCode() + "状态已操作审核,不允许回退!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                operationAccount = accountCountForCompanyMapper.queryFirstByVGsBm(fbaBox1.getCodeCompany());
                if (operationAccount == null){
                    apiResponse.setMsg("运营公司实时资金不存在,请核实后再操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                //查询仓储部绑定账户
                sysAccountBandDept = sysAccountBandDeptMapper.findByAccountId("CCB");
                if (sysAccountBandDept == null){
                    apiResponse.setMsg("仓储部绑定账户未启用或不存在,请核实后再操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                // 仓储部绑定账户增加物流费用
                warehousingAccount = accountCountForCompanyMapper.queryFirstByVGsBm(sysAccountBandDept.getvGsBm());
                if (warehousingAccount == null){
                    apiResponse.setMsg("仓储部实时资金不存在,请核实后再操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                String shipmentId =  fbaBox1.getShipmentId();
                if ("手动".equals(fbaBox.getCreationMethod())) {
                    fbaBox1.setShipmentId("");
                    fbaBox1.setDestinationFulfillmentCenterId("");
                }
                //头程冻结的实际物流费用
                priceTranPredict1 = Double.valueOf(fbaBox1.getActualLogisticsFreight().toString());

                //将完成单回退
                fbaBox1.setTrackingCode("");
                fbaBox1.setState("2");//已装箱状态
                fbaBox1.setStateName("已装箱");
                if (fbaBox1.getIsfmb() != null){
                    if (fbaBox1.getIsfmb() == 0){
                        fbaBox1.setStatePrint("2");
                        fbaBox1.setStatePrintName("配货清单和商品标已打印");
                    } else {
                        fbaBox1.setStatePrint("3");
                        fbaBox1.setStatePrintName("配货清单和商品标和透明标已打印");
                    }
                }
                fbaBox1.setStateTrack("0");
                fbaBox1.setStateTrackName("无");
                fbaBox1.setAuditUser(null);
                fbaBox1.setAuditTime(null);
                fbaBox1.setBoxMarkUser(null);
                fbaBox1.setBoxMarkTime(null);
                fbaBox1.setDeliveryUser(null);
                fbaBox1.setDeliveryTime(null);
                if (fbaBox1.getCreationMethod().equals("手动")) {
                    fbaBox1.setWarehouseSurchargePrice(BigDecimal.ZERO);
                    //先减去之前增加的仓库附加费
                    fbaBox1.setPriceTranCalWeightPredict(fbaBox1.getPriceTranCalWeightPredict().subtract(fbaBox1.getWarehouseSurcharge()));
                    fbaBox1.setActualLogisticsFreight(fbaBox1.getActualLogisticsFreight().subtract(fbaBox1.getWarehouseSurcharge()));
                    if (fbaBox1.getLoadDelivery().equals("是")) {
                        fbaBox1.setPriceTranCalWeightPredictPf(fbaBox1.getPriceTranCalWeightPredictPf().subtract(fbaBox1.getWarehouseSurchargePf()));
                        fbaBox1.setActualLogisticsFreightPf(fbaBox1.getActualLogisticsFreightPf().subtract(fbaBox1.getWarehouseSurchargePf()));
                        fbaBox1.setWarehouseSurchargePf(BigDecimal.ZERO);
                    }
                    fbaBox1.setWarehouseSurcharge(BigDecimal.ZERO);
                }
                fbaBoxMapper.updateByGuid(fbaBox1);
                //查询头程货件详情信息
                params1 = new HashMap<String, Object>();
                //头程计划单下所有箱子数据
                params1.put("codeBox1", fbaBox.getCode());
                fbaBoxDetailList = fbaBoxDetailMapper.findFbaBoxDetail(params1);

                if (fbaBoxDetailList.size() == 0) {
                    apiResponse.setMsg("头程单名下的商品信息不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                //计算装箱物料费 + 透明计划贴标费
                boxProject = Double.valueOf(fbaBox1.getNumBox()) * 15;

                transparencyProject = 0.0;
                Map<Integer, Integer> numBiDc;
                numBiDc = new HashMap<>();
                if (fbaBoxDetailList.size() != 0) {
                    for (int i = 0; i < fbaBoxDetailList.size(); i++) {
                        fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(i).getProductInfo(), FbaBoxDetail.class);
                        for (int j = 0; j < fbaBoxDetailListNew.size(); j++) {
                            if (numBiDc.get(j) == null) {
                                numBiDc.put(j, new Integer(fbaBoxDetailListNew.get(j).getNumRealityDeliver().equals("") ? "0" : fbaBoxDetailListNew.get(j).getNumRealityDeliver()));
                            } else {
                                numBiDc.put(j, numBiDc.get(j) + (new Integer(fbaBoxDetailListNew.get(j).getNumRealityDeliver().equals("") ? "0" : fbaBoxDetailListNew.get(j).getNumRealityDeliver())));
                            }
                        }
                    }
                    fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(0).getProductInfo(), FbaBoxDetail.class);
                    stringBuffer = new StringBuffer();
                    for (int j = 0; j < fbaBoxDetailListNew.size(); j++) {
                        //修改库存总数量
                        updateNum(fbaBox1,fbaBoxDetailListNew.get(j), apiResponse, userInfo, 1, numBiDc.get(j));
                        if (apiResponse.getCode() == 400) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                        if (!fbaBoxDetailListNew.get(j).getvDFilesDefault().equals("无附件")){
                            //详情备注赋值
                            stringBuffer.append(fbaBoxDetailListNew.get(j).getCommodityCode()+",数量"+numBiDc.get(j)+"个,");
                            //累加透明计划贴标费
                            transparencyProject = transparencyProject + (Double.valueOf(numBiDc.get(j)) * (0.6));
                        }
                        for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailList) {
                            fbaBoxDetai.setTrackingCode(null);
                            fbaBoxDetailMapper.updateByGuid(fbaBoxDetai);
                        }
                    }
                }

                if (fbaBox1.getIsDeliver() != 1) {
//                    查询物流部账号
                    sysAccountBandDept = sysAccountBandDeptMapper.findByAccountId("WLB");
                    if (sysAccountBandDept == null) {
                        apiResponse.setMsg("物流部门绑定账户未启用或不存在,请核实后再操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

                    // 物流公司增加物流费用
                    logisticsAccount = accountCountForCompanyMapper.queryFirstByVGsBm(sysAccountBandDept.getvGsBm());
                    if (logisticsAccount == null) {
                        apiResponse.setMsg("物流公司实时资金不存在,请核实后再操作!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

//                    资金流水(物流部 - 运营公司 头程物流费)
                    addAccountDetailedForCompany(operationAccount, logisticsAccount, userInfo, -priceTranPredict1,
                            "(回退)头程物流费，头程计划单:" + fbaBox1.getCodePlan() + "," + shipmentId + "," + fbaBox1.getNameLogsticsWay(),
                            "物流服务→头程运费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                    );
                    //物流部减少头程物流费
                    logisticsAccount.setfJe(logisticsAccount.getfJe() - priceTranPredict1);
                    accountCountForCompanyMapper.updateAccountCountForCompany(logisticsAccount);

                    //资金流水(运营公司 - 物流部 头程物流费)
                    addAccountDetailedForCompany(logisticsAccount, operationAccount, userInfo, priceTranPredict1,
                            "(回退)头程物流费，头程计划单:" + fbaBox1.getCodePlan() + "," + shipmentId + "," + fbaBox1.getNameLogsticsWay(),
                            "物流服务→头程运费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                    );
                    //运营公司增加头程物流费
                    operationAccount.setfJe(operationAccount.getfJe() + priceTranPredict1);

                    //资金流水(仓储部 - 运营公司 纸箱包装费)
                    addAccountDetailedForCompany(operationAccount, warehousingAccount, userInfo, -boxProject,
                            "(回退)纸箱费，头程计划单:" + fbaBox1.getCodePlan() + ",纸箱个数" + fbaBox1.getNumBox(),
                            "仓储服务→纸箱费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                    );
                    //仓储部减少纸箱包装费
                    warehousingAccount.setfJe(warehousingAccount.getfJe() - boxProject);

                    //资金流水(运营公司 - 仓储部 纸箱包装费)
                    addAccountDetailedForCompany(warehousingAccount, operationAccount, userInfo, boxProject,
                            "(回退)纸箱费，头程计划单:" + fbaBox1.getCodePlan() + ",纸箱个数" + fbaBox1.getNumBox(),
                            "仓储服务→纸箱费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                    );
                    //运营公司增加纸箱包装费
                    operationAccount.setfJe(operationAccount.getfJe() + boxProject);

                    if (stringBuffer.length() != 0) {
                        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                    }
                    if (transparencyProject != 0.0) {
                        //资金流水(仓储部-运营公司 透明计划贴标费用)
                        addAccountDetailedForCompany(operationAccount, warehousingAccount, userInfo, -transparencyProject,
                                "(回退)透明计划贴标费用，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + "," + stringBuffer,
                                "仓储服务→透明计划贴标费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                        );
                        //仓储部减少 透明计划贴标费用
                        warehousingAccount.setfJe(warehousingAccount.getfJe() - transparencyProject);

                        //资金流水(运营公司-仓储部 透明计划贴标费用)
                        addAccountDetailedForCompany(warehousingAccount, operationAccount, userInfo, transparencyProject,
                                "(回退)透明计划贴标费用，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() +"," + stringBuffer,
                                "仓储服务→透明计划贴标费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                        );
                        //更新仓储部
                        accountCountForCompanyMapper.updateAccountCountForCompany(warehousingAccount);

                        //更新运营公司
                        accountCountForCompanyMapper.updateAccountCountForCompany(operationAccount);
                    }
                }
                //海外仓逻辑
                if (fbaBox1.getIsDeliver() == 1){
                    delHwTailprogram(apiResponse,fbaBox1);
                    if (apiResponse.getCode() == 400){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                }
                try {
                    businessMapper.insertBatchNew(accountList);
                }catch (Exception e){
                    apiResponse.setMsg("新增账户流水单失败!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
            }
            apiResponse.setMsg("回退成功");
            apiResponse.setCode(0);
        } catch (Exception e) {
            if (e.getMessage().equals("Error getting LWA Access Token")) {
                apiResponse.setMsg("获取该网店令牌失败,请核实该店铺是否有权限!");
            }else if (e.getMessage().equals("Bad Request")) {
                apiResponse.setMsg("上传亚马逊货件数据出错,请核实数据再操作!");
            } else {
                apiResponse.setMsg("回退失败!");
                apiResponse.setCode(400);
            }
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }



    private void addShipment(FbaPlanOrder fbaPlanOrder,Address harvestAddress,InboundShipmentPlan inboundShipmentPlan,FbaShipment fbaShipment,UserInfo userInfo,ApiResponse apiResponse){
        try {
            ModuleNidAndBid moduleNidAndBid;
            Map<String, Object> params2;
            //查询头程货件最新数据
            params2 = new HashMap<String, Object>();
            params2.put("moduleTable", "TP_FbaShipment");
            moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params2);    //有事务控制，制单异常不跳过单号
            //新增头程货件单
            fbaShipment.setGuid(RandomValueUtils.getGUID());
            BeanUtils.copyProperties(fbaPlanOrder, fbaShipment);
            fbaShipment.setNid("0");
            fbaShipment.setCode(moduleNidAndBid.getBid());
            fbaShipment.setCreateTime(new Date());
            fbaShipment.setCid(userInfo.getCid());
            fbaShipment.setCidName(userInfo.getCidName());
            fbaShipment.setbUser(userInfo.getUserId());
            fbaShipment.setbUserName(userInfo.getUserName());
            fbaShipment.setbDept(userInfo.getDeptPath());
            fbaShipment.setbDeptName(userInfo.getDeptName());
            fbaShipment.setbPosition(userInfo.getPositionNameDa());
            fbaShipment.setaUser(userInfo.getUserId());
            fbaShipment.setaUserName(userInfo.getUserName());
            fbaShipment.setaDept(userInfo.getDeptPath());
            fbaShipment.setaDeptName(userInfo.getDeptName());
            fbaShipment.setaPosition(userInfo.getPositionNameDa());
            fbaShipment.setCodePlan(fbaPlanOrder.getCode());
            //设置收货地址
            fbaShipment.setName(harvestAddress.getName());
            fbaShipment.setDistrictOrCounty(harvestAddress.getDistrictOrCounty());
            fbaShipment.setAddressLine1(harvestAddress.getAddressLine1());
            fbaShipment.setAddressLine2(harvestAddress.getAddressLine2());
            fbaShipment.setCity(harvestAddress.getCity());
            fbaShipment.setStateOrProvinceCode(harvestAddress.getStateOrProvinceCode());
            fbaShipment.setCountryCode(harvestAddress.getCountryCode());
            fbaShipment.setPostalCode(harvestAddress.getPostalCode());
            fbaShipment.setDestinationFulfillmentCenterId(inboundShipmentPlan.getDestinationFulfillmentCenterId());
            if ("自动".equals(fbaPlanOrder.getCreationMethod())) {
                fbaShipment.setState("0");
                fbaShipment.setCurrencyAmount(inboundShipmentPlan.getEstimatedBoxContentsFee().getTotalFee().getValue());
                fbaShipment.setCurrency(inboundShipmentPlan.getEstimatedBoxContentsFee().getTotalFee().getCurrencyCode().getValue());
            } else {
                fbaShipment.setState("1");
            }
            fbaShipment.setAuditTime(new Date());
            fbaShipment.setAuditUser(userInfo.getUserId());
            fbaShipment.setShipmentId(inboundShipmentPlan.getShipmentId());
            fbaShipment.setvZdbz(fbaPlanOrder.getvZdbz());
            fbaShipment.setZysx(fbaPlanOrder.getZysx());
            fbaShipment.setPriceClearanceOpe(fbaPlanOrder.getPriceClearanceOpe());
            fbaShipment.setCoefficientWeight(fbaPlanOrder.getCoefficientWeight());
            fbaShipment.setToPurchasePrice(fbaPlanOrder.getToPurchasePrice());
            fbaShipment.setPriceSingleBoxReq(fbaPlanOrder.getPriceSingleBoxReq());
            fbaShipment.setLogisticsMmodeGuid(fbaPlanOrder.getLogisticsMmodeGuid());
            fbaShipment.setNumFreeProNameNew(fbaPlanOrder.getNumFreeProNameNew());
            fbaShipment.setIsDeliver(fbaPlanOrder.getIsDeliver());
            fbaShipment.setWarehouseAddress(fbaPlanOrder.getWarehouseAddress());
            fbaShipment.setPriceSingleBoxReqZd(fbaPlanOrder.getPriceSingleBoxReqZd());
            fbaShipmentMapper.insertFbaShipment(fbaShipment);
        }catch (Exception e){
            apiResponse.setMsg("新增货件信息失败!");
            apiResponse.setCode(400);
            return;
        }

    }

    private void addShipmentDetail(FbaPlanOrderDetail fbaPlanOrderDetail,FbaShipment fbaShipment,UserInfo userInfo,ApiResponse apiResponse){
        try {
            //新增头程货件详情信息
            FbaShipmentDetail fbaShipmentDetail = new FbaShipmentDetail();
            BeanUtils.copyProperties(fbaPlanOrderDetail, fbaShipmentDetail);
            fbaShipmentDetail.setGuid(RandomValueUtils.getGUID());
            fbaShipmentDetail.setCodeShipmentOrder(fbaShipment.getCode());
            fbaShipmentDetail.setBUser(userInfo.getUserId());
            fbaShipmentDetail.setBDept(userInfo.getDeptPath());
            fbaShipmentDetail.setCreateUser(userInfo.getUserId());
            fbaShipmentDetail.setCreateTime(new Date());
            fbaShipmentDetail.setPdGuid(fbaPlanOrderDetail.getGuid());
            fbaShipmentDetail.setSpGuid(fbaPlanOrderDetail.getSpGuid());
            fbaShipmentDetail.setIsSign(fbaPlanOrderDetail.getIsSign());
            fbaShipmentDetail.setGaugeMaintenanceId(fbaPlanOrderDetail.getGaugeMaintenanceId());
            fbaShipmentDetail.setGaugeMaintenanceNum(fbaPlanOrderDetail.getGaugeMaintenanceNum());
            fbaShipmentDetail.setSignCode(fbaPlanOrderDetail.getSignCode());
            fbaShipmentDetail.setvSfJp(fbaPlanOrderDetail.getvSfJp());
            fbaShipmentDetailMapper.insertFbaShipmentDetail(fbaShipmentDetail);
        }catch (Exception e){
            apiResponse.setMsg("新增货件详情失败!");
            apiResponse.setCode(400);
        }

    }

    private void getAmazonShop(AmazonShop amazonShop,Address address,SellerSecretsVO secretsVO) {
        //查询网店信息
        if (amazonShop != null) {
            address.setName(amazonShop.getName());
            address.setAddressLine1(amazonShop.getAddressLine1());
            address.setAddressLine2(amazonShop.getAddressLine2());
            address.setDistrictOrCounty(amazonShop.getDistrictOrCounty());
            address.setCity(amazonShop.getCity());
            address.setStateOrProvinceCode(amazonShop.getStateOrProvinceCode());
//            address.setCountryCode(amazonShop.getCountryCode());
            address.setCountryCode("CN");
            address.setPostalCode(amazonShop.getPostalCode());

            secretsVO.setAWSAuthenticationCredentials_AK(ApiConfig.getAmazonAwsAccessKey());
            secretsVO.setAWSAuthenticationCredentials_SK(ApiConfig.getAmazonAwsAccessSecret());
            secretsVO.setAWSAuthenticationCredentialsProvider_roleArn(ApiConfig.getAmazonRoleArn());
            secretsVO.setlWAAuthorizationCredentials_clientid(ApiConfig.getAmazonLwaClientKey());
            secretsVO.setLWAAuthorizationCredentials_clientSecret(ApiConfig.getAmazonLwaClientSecret());
            secretsVO.setSeller_id(amazonShop.getSellerId());
            secretsVO.setLWAAuthorizationCredentials_refreshToken(amazonShop.getRefreshToken());

            if ("欧洲".equals(amazonShop.getRegionName())) {
                secretsVO.setMarketPlace(MarketplaceEnum.EUROPE.getCode());
            } else if ("北美".equals(amazonShop.getRegionName())) {
                secretsVO.setMarketPlace(MarketplaceEnum.NORTH.getCode());
            } else if ("远东".equals(amazonShop.getRegionName())) {
                secretsVO.setMarketPlace(MarketplaceEnum.ASIA.getCode());
            } else {
//                throw new RuntimeException(amazonShop.getShopName() + "地区名称不合规!");
            }
        }
    }

    private void addBox(FbaBoxDetail fbaBoxDetail,HSSFCell cell,HSSFRow row,AmazonShop amazonShop){
        JSONArray boxList =  JSONArray.parseArray(fbaBoxDetail.getBoxList());
        if (boxList.size() != 0){
            for (int i = 0; i <boxList.size(); i++) {
                cell = row.createCell(10+i);
                cell.setCellValue(new Double(boxList.get(i).toString()));
                if (!amazonShop.getRegionName().equals("欧洲")){
                    if (fbaBoxDetail.getSerial().equals("箱重(kg)")){
                        cell.setCellValue(new Double(new BigDecimal(boxList.get(i).toString()).multiply(new BigDecimal(2.205)).setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
                    }
                    if (fbaBoxDetail.getSerial().equals("箱规长(cm)") ||
                            fbaBoxDetail.getSerial().equals("箱规宽(cm)") ||
                            fbaBoxDetail.getSerial().equals("箱规高(cm)")){
                        cell.setCellValue(new Double(new BigDecimal(boxList.get(i).toString()).multiply(new BigDecimal(0.3937008)).setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
                    }
                }
            }
        }
    }

    public static Boolean upload(byte[] source, String url, String contentType,Integer type,FbaBox fbaBox,List<FbaBoxDetail> fbaBoxDetaiList) {
        OkHttpClient client = new OkHttpClient();
        Request request;
        try {
            if (type == 1) {
                request = new Request.Builder()
                        .url(url).get().build();
            } else {
                request = new Request.Builder()
                        .url(url)
                        .put(RequestBody.create(MediaType.parse(contentType), source))
                        .build();
            }

            Response response = client.newCall(request).execute();
            System.out.println("上传结果:" + response.message());
            if (type == 1) {
                String asds = response.body().string();
                String asd = "Number of records processed\t\t" + (fbaBoxDetaiList.size()-4);
                String ss = "Number of records successful\t\t" + (fbaBoxDetaiList.size()-4);
                System.out.println("get返回结果：" + asds);
                System.out.println("长度：" + asds.length());//91的长度为正确
                System.out.println(asds.indexOf(asd));
                System.out.println(asds.indexOf(ss));
                if (asds.indexOf(asd) == -1 || asds.indexOf(ss) == -1){
                    return false;
                } else {
                    return true;
                }
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return true;
    }


    private void addDevanning(FbaBox fbaBox,Map<String, Object> params,FbaDevanning fbaDevanning,UserInfo userInfo,ApiResponse apiResponse,FbaShipment fbaShipment1,int type){
        try {
            ModuleNidAndBid moduleNidAndBid;
            Map<String, Object> params2;
            //查询头程货件最新数据
            params2 = new HashMap<String, Object>();
            params2.put("moduleTable", "TP_FbaDevanning");
            moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params2);
            //新增拆箱单数据
            fbaDevanning.setCodeBox(fbaBox.getCode());
            fbaDevanning.setCodePlanOrder(fbaBox.getCodePlan());
            fbaDevanning.setCodeDevanning(moduleNidAndBid.getBid());
            fbaDevanning.setCodeCompany(fbaBox.getCodeCompany());
            fbaDevanning.setNameCompany(fbaBox.getNameCompany());
            fbaDevanning.setRemark(params.get("remark").toString());
            fbaDevanning.setState("0");
            fbaDevanning.setCreateUser(userInfo.getUserId());
            fbaDevanning.setCreateTime(new Date());
            fbaDevanning.setGuid(RandomValueUtils.getGUID());
            fbaDevanning.setIid(0);
            fbaDevanning.setNid(moduleNidAndBid.getNid());
            fbaDevanning.setBid(moduleNidAndBid.getBid());
            fbaDevanning.setCid(userInfo.getCid());
            fbaDevanning.setCidName(userInfo.getCidName());
            fbaDevanning.setbUser(userInfo.getUserId());
            fbaDevanning.setbUserName(userInfo.getUserName());
            fbaDevanning.setbDept(userInfo.getDeptPath());
            fbaDevanning.setbDeptName(userInfo.getDeptName());
            fbaDevanning.setbPosition(userInfo.getPositionNameDa());
            fbaDevanning.setaUser(userInfo.getUserId());
            fbaDevanning.setaUserName(userInfo.getUserName());
            fbaDevanning.setaDept(userInfo.getDeptPath());
            fbaDevanning.setaDeptName(userInfo.getDeptName());
            fbaDevanning.setaPosition(userInfo.getPositionNameDa());
            fbaDevanning.setCreateTime(new Date());
            fbaDevanning.setShipmentId(fbaBox.getShipmentId());
            fbaDevanning.setCodeDispatch(fbaBox.getCodeShipment());
            fbaDevanning.setvGsJc(fbaBox.getvGsJc());
            fbaDevanning.setWeightReal(fbaBox.getWeightReal());
            fbaDevanning.setUpdateUser(fbaBox.getUpdateUser());
            fbaDevanning.setPackingPerson(fbaBox.getPackingPerson());
            fbaDevanning.setNumBox(fbaBox.getNumBox());
            fbaDevanning.setCreationMethod(fbaBox.getCreationMethod());
            if (type == 0){
                fbaDevanning.setState("0");
                fbaDevanning.setStateNameCx("1");
                fbaDevanning.setStateNameCxName("是");
                fbaDevanning.setStateNameZx("1");
                fbaDevanning.setStateNameZxName("是");
            }else if (type == 1){
                fbaDevanning.setState("1");
                fbaDevanning.setUpdateTime(new Date());
                fbaDevanning.setAuditTime(new Date());
                fbaDevanning.setAuditUser(userInfo.getUserId());
                fbaDevanning.setStateNameCx("0");
                fbaDevanning.setStateNameCxName("否");
                fbaDevanning.setStateNameZx("0");
                fbaDevanning.setStateNameZxName("否");
            }
            fbaDevanningMapper.insertFbaDevanning(fbaDevanning);
        }catch (Exception e){
            apiResponse.setMsg("新增拆箱单失败!");
            apiResponse.setCode(400);
        }
    }


    private void updateNum(FbaBox fbaBox,FbaBoxDetail item ,ApiResponse apiResponse,UserInfo userInfo,Integer type,Integer tolNum){
        try {
            StockControl oldData;
            StockControl stockControl = new StockControl();
            if (item.getGuidKc() != null && !item.getGuidKc().equals("")) {
                Map<String, Object> params2 = new HashMap<String, Object>();
                params2.put("rkGuid", item.getRkGuid());
                params2.put("vGsBm", item.getvGsBm());
                params2.put("vHw", item.getCodeStockLocation());
                params2.put("vKq", item.getCodeStockArea());
                params2.put("gDepot", item.getCodeStockOn());
                params2.put("productcode", item.getCommodityCode());
                oldData = storageMapper.findByMultiparameter(params2);
                if (oldData != null) {
                    BeanUtils.copyProperties(oldData, stockControl);
                    //获取实际发货数量
                    if (type == 0) {
                        //总数量-实际计划发货
                        stockControl.setProductNumAll(oldData.getProductNumAll() - tolNum <= 0 ? 0 : oldData.getProductNumAll() - tolNum);
                        stockControl.setProductNum(stockControl.getProductNum() + (Integer.valueOf(item.getNumPlanDeliver()) - tolNum));
                        if (oldData.getProductNumAll() < tolNum) {
                            apiResponse.setMsg("库存数量不足!");
                            apiResponse.setCode(400);
                        } else {
                            storageMapper.update(stockControl);
                            addUpdateLog("TP_FbaBox", stockControl.getGuid(), oldData, stockControl, "头程装箱审核总数量扣减计划发货数量", userInfo);
                        }
                    } else if (type == 1) {
                        //将库存数量返回
                        stockControl.setProductNumAll(oldData.getProductNumAll() + tolNum);
                        stockControl.setProductNum(stockControl.getProductNum() - (Integer.valueOf(item.getNumPlanDeliver()) - tolNum));
                        storageMapper.update(stockControl);
                        addUpdateLog("TP_FbaBox", stockControl.getGuid(), oldData, stockControl, "头程装箱审核总数量回填计划发货数量", userInfo);
                    } else if (type == 2) {
                        //将库存数量返回
                        stockControl.setProductNum(oldData.getProductNum() + (Integer.valueOf(item.getNumPlanDeliver())));
                        storageMapper.update(stockControl);
                        addUpdateLog("TP_FbaBox", stockControl.getGuid(), oldData, stockControl, "头程装箱取消单总数量回填计划发货数量", userInfo);
                    }else if (type == 3) {
                        //将库存数量返回
                        stockControl.setProductNumAll(oldData.getProductNumAll() + tolNum);
                        stockControl.setProductNum(stockControl.getProductNum() - (Integer.valueOf(item.getNumPlanDeliver()) - tolNum));
                        storageMapper.update(stockControl);
                        addUpdateLog("TP_FbaBox", stockControl.getGuid(), oldData, stockControl, "头程完成单拆箱总数量回填计划发货数量", userInfo);
                    }else if (type == 4) {
                        //将库存数量返回
                        stockControl.setProductNumAll(oldData.getProductNumAll() + tolNum);
                        stockControl.setProductNum(stockControl.getProductNum() - (Integer.valueOf(item.getNumPlanDeliver()) - tolNum));
                        storageMapper.update(stockControl);
                        addUpdateLog("TP_FbaBox", stockControl.getGuid(), oldData, stockControl, "头程完成单拆箱总数量回填计划发货数量,并且复建新的装箱单号", userInfo);
                    }

                    // 新库存添加库存流水
                    StockControlRunning stockControlRunning = new StockControlRunning();
                    stockControlRunning.setGuid(RandomValueUtils.getGUID());
                    stockControlRunning.setGuidStockControl(stockControl.getGuid());
                    stockControlRunning.setBidRelative(fbaBox.getCode());
                    stockControlRunning.setLocationHw(item.getCodeStockLocation());
                    stockControlRunning.setProductCode(item.getCommodityCode());
                    stockControlRunning.setvGsBm(item.getvGsBm());
                    stockControlRunning.setCreateTime(new Date());
                    stockControlRunning.setProductNumLeft(stockControl.getProductNumAll());
                    if (type == 0) {
                        stockControlRunning.setProductNumChange(-(tolNum));
                        stockControlRunning.setRemark("头程装箱审核总数量扣减计划发货数量 可用数量回填:" + (Integer.valueOf(item.getNumPlanDeliver()) - tolNum));
                    } else if (type == 1) {
                        stockControlRunning.setProductNumChange(tolNum);
                        stockControlRunning.setRemark("头程装箱审核总数量回填计划发货数量  可用数量扣减:" + "-" + (Integer.valueOf(item.getNumPlanDeliver()) - tolNum));
                    }else if (type == 3){
                        stockControlRunning.setProductNumChange(tolNum);
                        stockControlRunning.setRemark("头程完成单拆箱总数量回填计划发货数量  可用数量扣减:" + "-"+(Integer.valueOf(item.getNumPlanDeliver()) - tolNum));
                    }else if (type == 4){
                        stockControlRunning.setProductNumChange(tolNum);
                        stockControlRunning.setRemark("头程完成单拆箱总数量回填计划发货数量  并且复建新的头程装箱单 可用数量扣减:" + "-"+(Integer.valueOf(item.getNumPlanDeliver()) - tolNum));
                    } else {
                        stockControlRunning.setProductNumChange(Integer.valueOf(item.getNumPlanDeliver()));
                        stockControlRunning.setRemark("头程装箱取消总数量回填计划发货数量  可用数量回填:" +(Integer.valueOf(item.getNumPlanDeliver())));
                    }

                    stockControlRunningMapper.insert(stockControlRunning);
                } else {
                    apiResponse.setMsg("库存信息不存在!");
                    apiResponse.setCode(400);
                }
            }
        }catch (Exception e) {
            apiResponse.setMsg("修改库存信息失败!");
            apiResponse.setCode(400);
        }
    }

    /**
     * 头程货件取消已装箱
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse unbox(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        List<FbaBox> list;
        UserInfo userInfo;
        List<FbaBoxDetail> fbaBoxDetailListNew = null;
        Map<String, Object> params1;
        List<FbaBoxDetail> fbaBoxDetailList;

        try {
            list = JSON.parseArray(params.get("infoItems").toString(), FbaBox.class);

            for (FbaBox fbaBox : list) {
                userInfo = userInfoMapper.findByUserId(fbaBox.getaUser());
                if (userInfo == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的用户不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

//                if ("手动".equals(fbaBox.getCreationMethod())) {
                FbaBox fbaBox1 = fbaBoxMapper.queryFirstByGuid(fbaBox.getGuid());
                if (fbaBox1 == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程单不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                } else if (!"2".equals(fbaBox1.getState())){
                    apiResponse.setMsg(fbaBox.getCode() + "单据只允许是已装箱状态,请核实后在操作!!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                } else if ("是".equals(fbaBox1.getIsBinning())){
                    apiResponse.setMsg(fbaBox.getCode() + "单据只允许是未分箱状态,请核实后在操作!!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                //将回退装箱状态
                fbaBox1.setState("0");
                fbaBox1.setStateName("未装箱");
                fbaBox1.setUpdateUser(null);
                fbaBox1.setUpdateTime(null);
                fbaBoxMapper.updateByGuid(fbaBox1);
//                }
            }
            apiResponse.setMsg("回退成功");
            apiResponse.setCode(0);
        } catch (Exception e) {
            if (e.getMessage().equals("Error getting LWA Access Token")) {
                apiResponse.setMsg("获取该网店令牌失败,请核实该店铺是否有权限!");
            }else if (e.getMessage().equals("Bad Request")) {
                apiResponse.setMsg("上传亚马逊货件数据出错,请核实数据再操作!");
            } else {
                apiResponse.setMsg("回退失败!");
                apiResponse.setCode(400);
            }
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResponse;
    }


    /**
     * 定时修改头程线上发货状态
     * @return
     */
    @Override
    @Transactional(timeout=1000,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse updateFbaInbound(FbaBox fbaBox,List<FbaLogsticsOrderDetail> fbaLogsticsOrderDetailListNew,
                                        List<FbaLogsticsOrderDetail> fbaLogsticsOrderDetailList, ApiResponse apiResponse,Map<String, Object> params){
        int insertLogId = 0;
        InboundShipmentRequest body;
        AmazonShop amazonShop;
        Address address;
        SellerSecretsVO secretsVO;
        InboundShipmentHeader inboundShipmentHeader;
        InboundShipmentItemList inboundShipmentItems;
        Map<String, Object> params1;
        List<FbaBoxDetail> fbaBoxDetailList;
        List<FbaBoxDetail> fbaBoxDetailListNew = null;
        InboundShipmentItem inboundShipmentItem ;
        FbaInboundApi api;
        File file;
        FileInputStream input;
        HSSFWorkbook workbook;
        HSSFSheet sheet;
        HSSFRow row;
        HSSFCell cell = null;
        Map<String, Object> params2;
        List<FbaBoxDetail> fbaBoxDetails;
        FbaBoxDetail fbaBoxDetailNew;
        FileOutputStream out;
        FbaInboundApi fbaInboundApi;
        FeedsApi feedsApi;
        //上传箱子数据putTransportDetails
        NonPartneredSmallParcelPackageInputList nonPartneredSmallParcelPackageInputs;
        NonPartneredSmallParcelDataInput nonPartneredSmallParcelDataInput;
        NonPartneredSmallParcelPackageInput nonPartneredSmallParcelPackageInput;
        TransportDetailInput transportDetailInput;
        PutTransportDetailsRequest putTransportDetailsRequest;
        PutTransportDetailsResponse putTransportDetailsResponse = null;
        InboundShipmentResponse response = null;
        try {
            body = new InboundShipmentRequest();

            //查询网店信息
            amazonShop = amazonShopMapper.findAmazonShopByGuid(fbaBox.getSellerId());
            if (amazonShop != null) {
                address = new Address();
                secretsVO = new SellerSecretsVO();
                getAmazonShop(amazonShop, address, secretsVO);

                inboundShipmentHeader = new InboundShipmentHeader();
                inboundShipmentHeader.setShipmentName(fbaBox.getShipmentId() + "-" + fbaBox.getDestinationFulfillmentCenterId());
                inboundShipmentHeader.setShipFromAddress(address);
                inboundShipmentHeader.setDestinationFulfillmentCenterId(fbaBox.getDestinationFulfillmentCenterId());
                inboundShipmentHeader.setShipmentStatus(ShipmentStatus.SHIPPED);
                inboundShipmentHeader.setLabelPrepPreference(LabelPrepPreference.SELLER_LABEL);
                inboundShipmentHeader.setIntendedBoxContentsSource(IntendedBoxContentsSource.FEED);

                inboundShipmentItems = new InboundShipmentItemList();
                //查询头程货件详情信息
                params1 = new HashMap<String, Object>();
                //头程计划单下所有箱子数据
                params1.put("codeBox1", fbaBox.getCode());
                fbaBoxDetailList = fbaBoxDetailMapper.findFbaBoxDetail(params1);

                if (fbaBoxDetailList.size() != 0) {
                    //将相同的sku、Asin、FnSku相加起来
                    Set<String> fnSkuList = new HashSet<>();
                    List<FbaBoxDetail> fbaBoxDetailListOld = new ArrayList<>();
                    for (FbaBoxDetail fbaBoxDetail : fbaBoxDetailList){
                        fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetail.getProductInfo(), FbaBoxDetail.class);
                        for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailListNew) {
                            fnSkuList.add(fbaBoxDetai.getFnsku());
                            fbaBoxDetailListOld.add(fbaBoxDetai);
                        }
                    }

                    List<FbaBoxDetail> fbaBoxDetailListApi;
                    BigDecimal numPlanDeliver;
                    for (String fnSku : fnSkuList) {
                        fbaBoxDetailListApi = fbaBoxDetailListOld.stream().filter(
                                fbaBoxDetail1 -> fbaBoxDetail1.getFnsku().equals(fnSku)
                        ).collect(Collectors.toList());
                        numPlanDeliver = BigDecimal.ZERO;
                        for (FbaBoxDetail fbaBoxDetail : fbaBoxDetailListApi){
                            numPlanDeliver = numPlanDeliver.add(new BigDecimal(fbaBoxDetail.getNumRealityDeliver().equals("")?"0":fbaBoxDetail.getNumRealityDeliver()));
                        }
                        inboundShipmentItem = new InboundShipmentItem();
                        inboundShipmentItem.setSellerSKU(fbaBoxDetailListApi.get(0).getSku());
                        inboundShipmentItem.setFulfillmentNetworkSKU(fbaBoxDetailListApi.get(0).getFnsku());
                        inboundShipmentItem.setQuantityShipped(Integer.valueOf(numPlanDeliver.toString()));
                        inboundShipmentItems.add(inboundShipmentItem);
                    }
                }

                body.setInboundShipmentHeader(inboundShipmentHeader);
                body.setInboundShipmentItems(inboundShipmentItems);
                body.setMarketplaceId(amazonShop.getMarketplaceIds());
                api = Helper.buildApi(secretsVO, FbaInboundApi.class);
                try {
                    response = api.updateInboundShipment(body, fbaBox.getShipmentId());
                }catch (Exception ex){
                    apiResponse.setMessage(ex.getMessage() + "updateInboundShipment失败!");
                    apiResponse.setCode(400);
                    return apiResponse;
                }

                fbaBox.setIsTracking("是");
                fbaBox.setTrackingTime(new Date());
                fbaBoxMapper.updateByGuid(fbaBox);

                fbaLogsticsOrderDetailListNew = fbaLogsticsOrderDetailList.stream().filter(
                        fbaLogsticsOrderDetail -> fbaLogsticsOrderDetail.getShipmentId().equals(fbaBox.getShipmentId())
                ).collect(Collectors.toList());
                if (fbaLogsticsOrderDetailListNew.size() != 0) {
                    fbaLogsticsOrderDetailListNew.get(0).setIsTracking("是");
                    fbaLogsticsOrderDetailListNew.get(0).setTrackingTime(new Date());
                }


                //查询详情数据
                params2 = new HashMap<String, Object>();
                params2.put("codeShipment", fbaBox.getCodeShipment());
                params2.put("num", "1");
                fbaBoxDetails = fbaBoxDetailService.queryAutoList(params2);

                int updateLength = fbaLogsticsOrderDetailList.size();
                int u = 0;
                while (updateLength > 10) {
                    fbaLogsticsOrderDetailMapper.batchUpdate(fbaLogsticsOrderDetailList.subList(u, u + 10));
                    u = u + 10;
                    updateLength = updateLength - 10;
                }
                if (updateLength > 0) {
                    fbaLogsticsOrderDetailMapper.batchUpdate(fbaLogsticsOrderDetailList.subList(u, u + updateLength));
                }

                try {
                    //根据数据生成表格
                    if (amazonShop.getRegionName().equals("欧洲")){
                        file = new File(ApiConfig.getUploadExcel() + "/poitest1.xlsx");
                    } else {
                        file = new File(ApiConfig.getUploadExcel() + "/poitest2.xlsx");
                    }
                    input = new FileInputStream(file);
                    // HSSFWorkbook用于操作后缀为.xls的excel表格，XSSFWorkbook用于操作.xlsx的excel表格
                    workbook = new HSSFWorkbook(input);
                    // 获取工作簿的方法有两种，一种是根据索引获取，第一个sheet的索引为0，还有一种是根据sheet名称获取
                    sheet = workbook.getSheetAt(0);
                    // 最后一行行号等于sheet的数据行数
                    for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
                        // 得到每一行
                        row = sheet.getRow(i);
                        //排除空白行
                        if (row == null && i == 2) {
                            continue;
                        }
                        if (i == 0) {
                            cell = row.getCell(1);
                            cell.setCellValue(fbaBox.getShipmentId());
                        } else if (i == 3) {
                            for (int j = 0; j < fbaBox.getNumBox(); j++) {
                                cell = row.createCell(10 + j);
                                cell.setCellValue("Box " + (j + 1) + " - QTY");
                            }
                        } else if (fbaBoxDetails.size() > 0 && i > 3 && i < 62) {
                            for (int k = 0; k < fbaBoxDetails.size() - 4; k++) {
                                fbaBoxDetailNew = fbaBoxDetails.get(k);
                                if (i == 4 + k) {
                                    cell = row.createCell(0);
                                    cell.setCellValue(fbaBoxDetailNew.getSku());
                                    cell = row.createCell(3);
                                    cell.setCellValue(fbaBoxDetailNew.getFnsku());
                                    cell = row.createCell(8);
                                    cell.setCellValue(new Double(fbaBoxDetailNew.getNumPlanDeliver()));
                                    cell = row.createCell(9);
                                    cell.setCellValue(new Double(fbaBoxDetailNew.getNumPlanDeliver()));

                                    addBox(fbaBoxDetailNew, cell, row,amazonShop);
                                }
                            }
                        } else if (i == 62) {
                            for (int j = 0; j < fbaBox.getNumBox(); j++) {
                                cell = row.createCell(10 + j);
                                cell.setCellValue("Box " + (j + 1));
                            }
                        } else if (i == 63) {
                            fbaBoxDetailNew = fbaBoxDetails.get(fbaBoxDetails.size() - 4);
                            addBox(fbaBoxDetailNew, cell, row,amazonShop);
                        } else if (i == 64) {
                            fbaBoxDetailNew = fbaBoxDetails.get(fbaBoxDetails.size() - 3);
                            addBox(fbaBoxDetailNew, cell, row,amazonShop);
                        } else if (i == 65) {
                            fbaBoxDetailNew = fbaBoxDetails.get(fbaBoxDetails.size() - 2);
                            addBox(fbaBoxDetailNew, cell, row,amazonShop);
                        } else if (i == 66) {
                            fbaBoxDetailNew = fbaBoxDetails.get(fbaBoxDetails.size() - 1);
                            addBox(fbaBoxDetailNew, cell, row,amazonShop);
                        }
                    }
                    sheet.shiftRows(61, 67, -(67 - 10 - (fbaBoxDetails.size() - 4)));
                    out = new FileOutputStream(ApiConfig.getUploadExcel() + "/" + fbaBox.getShipmentId() + ".xlsx");
                    workbook.write(out);
                    out.close();
                    // 关闭资源
                    workbook.close();
                } catch (Exception e) {
                    apiResponse.setMessage(fbaBox.getCode() + "生成Excel表格失败!");
                    apiResponse.setCode(400);
                    return apiResponse;
                }
                nonPartneredSmallParcelPackageInputs = new NonPartneredSmallParcelPackageInputList();
                nonPartneredSmallParcelDataInput = new NonPartneredSmallParcelDataInput();
                nonPartneredSmallParcelDataInput.setCarrierName("other");
                nonPartneredSmallParcelDataInput.setPackageList(nonPartneredSmallParcelPackageInputs);
                for (int i = 0; i < fbaBoxDetailList.size(); i++) {
                    nonPartneredSmallParcelPackageInput = new NonPartneredSmallParcelPackageInput();
                    nonPartneredSmallParcelPackageInput.setTrackingId(fbaBoxDetailList.get(i).getTrackingCode());
                    nonPartneredSmallParcelPackageInputs.add(nonPartneredSmallParcelPackageInput);
                }
                transportDetailInput = new TransportDetailInput();
                transportDetailInput.setNonPartneredSmallParcelData(nonPartneredSmallParcelDataInput);

                putTransportDetailsRequest = new PutTransportDetailsRequest();
                putTransportDetailsRequest.setIsPartnered(false);
                putTransportDetailsRequest.setShipmentType(ShipmentType.SP);
                putTransportDetailsRequest.setTransportDetails(transportDetailInput);

                api = Helper.buildApi(secretsVO, FbaInboundApi.class);
                try {
                    putTransportDetailsResponse = api.putTransportDetails(fbaBox.getShipmentId(), putTransportDetailsRequest);
                }catch (Exception ex){
                    apiResponse.setMessage(fbaBox.getCode() + "putTransportDetails失败!");
                    apiResponse.setCode(400);
                    return apiResponse;
                }
                apiLogService.addApiLog("api", "CancelParcel", "putTransportDetailsRequest：" + putTransportDetailsRequest.toString() + "," + "response:" + response.getPayload(), "", 0, "更新物流信息putTransportDetails成功!");

                if (putTransportDetailsResponse.getErrors() == null) {
                    String contentType = "application/vnd.ms-excel";
                    CreateFeedDocumentSpecification createFeedDocumentSpecification = new CreateFeedDocumentSpecification();
                    createFeedDocumentSpecification.setContentType(contentType);
                    feedsApi = Helper.buildApi(secretsVO, FeedsApi.class);
                    CreateFeedDocumentResponse createFeedDocumentResponse = feedsApi.createFeedDocument(createFeedDocumentSpecification);
                    String feedDocumentId = createFeedDocumentResponse.getFeedDocumentId();
                    String url = createFeedDocumentResponse.getUrl();

                    String filePath = ApiConfig.getUploadExcel() + "/" + fbaBox.getShipmentId() + ".xlsx";
                    byte[] source = null;
                    try {
                        source = Files.readAllBytes(Paths.get(filePath));
                    } catch (IOException e) {
                        apiResponse.setMessage(fbaBox.getCode() + "打开xlsx失败!");
                        apiResponse.setCode(400);
                        return apiResponse;
                    }
                    if (source == null) {
                        apiResponse.setMessage("文件读取错误");
                        apiResponse.setCode(400);
                        return apiResponse;
                    }
                    upload(source, url, contentType, 0, fbaBox,fbaBoxDetails);
                    CreateFeedSpecification createFeedSpecification = new CreateFeedSpecification();
                    createFeedSpecification.setFeedType("POST_FLAT_FILE_FROM_EXCEL_FBA_CREATE_CARTON_INFO");
                    createFeedSpecification.setMarketplaceIds(Collections.singletonList(amazonShop.getMarketplaceIds()));
                    createFeedSpecification.setInputFeedDocumentId(feedDocumentId);
                    CreateFeedResponse createFeedResponse = feedsApi.createFeed(createFeedSpecification);
                    String feedId = createFeedResponse.getFeedId();
                    Feed feed;
                    while (true) {
                        feed = feedsApi.getFeed(feedId);
                        if (feed.getProcessingStatus() != Feed.ProcessingStatusEnum.DONE) {
                            try {
                                TimeUnit.SECONDS.sleep(2);
                            } catch (InterruptedException ignored) {
                                apiResponse.setMessage("访问feed失败!");
                                apiResponse.setCode(400);
                                return apiResponse;
                            }
                        } else {
                            break;
                        }
                    }
                    String resultFeedDocumentId = feed.getResultFeedDocumentId();
                    FeedDocument feedDocument = null;
                    try {
                        feedDocument = feedsApi.getFeedDocument(resultFeedDocumentId);
                    }catch (Exception ex){
                        apiResponse.setMessage("访问feed失败!");
                        apiResponse.setCode(400);
                        return apiResponse;
                    }
                    System.out.println(feedDocument);
                    Boolean upload = upload(source, feedDocument.getUrl(), contentType, 1, fbaBox,fbaBoxDetails);
                    Path path2 = Paths.get(filePath);
                    Files.delete(path2);
                    if (upload == false) {
                        apiResponse.setCode(500);
                        apiResponse.setMessage("上传箱子数据失败!");
                        return apiResponse;
                    }

                }
            }else {
                apiResponse.setMessage(fbaBox.getCode() + "头程单名下的店铺不存在!");
                apiResponse.setCode(400);
                return apiResponse;
            }
        }catch (Exception e){
            apiResponse.setCode(400);
            apiResponse.setMessage("定时修改头程线上发货状态出错，具体错误信息为："+e.getMessage());
            logger.error("定时修改头程线上发货状态出错，错误信息为：" + e.getMessage());
            return apiResponse;
        }
        apiResponse.setSuccess(true);
        apiResponse.setCode(0);
        return apiResponse;
    }

    /**
     * 上传头程追踪编号
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse uploadtraceNumber(Map<String, Object> params) throws Exception{
        ApiResponse apiResponse = new ApiResponse();
        String shipmentId = params.get("shipmentId").toString();
        List<String> shipmentIdList = new ArrayList<>();
        shipmentIdList.add(shipmentId);
        List<FbaBox> list = fbaBoxMapper.queryFirstByShipmentIdList(shipmentIdList);
        List<FbaLogsticsOrderDetail> fbaLogsticsOrderDetailList = null;
        if (params.get("type").equals("0")){
            fbaLogsticsOrderDetailList = fbaLogsticsOrderDetailMapper.queryFirstByShipmentIdList(shipmentIdList);
        }else {
            for (FbaBox fbaBox :list){
                if (fbaBox.getCreationMethod().equals("手动")){
                    apiResponse.setCode(400);
                    apiResponse.setMsg(shipmentId+"不是自动状态,不允许操作!");
                    return apiResponse;
                }
            }
        }
        if (list.size() == 0){
            apiResponse.setCode(400);
            apiResponse.setMsg("FBA"+shipmentId+"不存在或者状态非导入追踪编号!");
            return apiResponse;
        }else {
            List<FbaLogsticsOrderDetail> fbaLogsticsOrderDetailListNew;
            int insertLogId = 0;
            InboundShipmentRequest body;
            AmazonShop amazonShop;
            Address address;
            SellerSecretsVO secretsVO;
            InboundShipmentHeader inboundShipmentHeader;
            InboundShipmentItemList inboundShipmentItems;
            Map<String, Object> params1;
            List<FbaBoxDetail> fbaBoxDetailList;
            List<FbaBoxDetail> fbaBoxDetailListNew = null;
            InboundShipmentItem inboundShipmentItem;
            FbaInboundApi api;
            File file;
            FileInputStream input;
            HSSFWorkbook workbook;
            HSSFSheet sheet;
            HSSFRow row;
            HSSFCell cell = null;
            Map<String, Object> params2;
            List<FbaBoxDetail> fbaBoxDetails;
            FbaBoxDetail fbaBoxDetailNew;
            FileOutputStream out;
            FbaInboundApi fbaInboundApi;
            FeedsApi feedsApi;
            //上传箱子数据putTransportDetails
            NonPartneredSmallParcelPackageInputList nonPartneredSmallParcelPackageInputs;
            NonPartneredSmallParcelDataInput nonPartneredSmallParcelDataInput;
            NonPartneredSmallParcelPackageInput nonPartneredSmallParcelPackageInput;
            TransportDetailInput transportDetailInput;
            PutTransportDetailsRequest putTransportDetailsRequest;
            PutTransportDetailsResponse putTransportDetailsResponse;
            InboundShipmentResponse response = null;

            for (FbaBox fbaBox : list) {
                try {
                    insertLogId = apiLogService.addApiLog("Amazon", "UpdateFbaInbound", "头程完成单[" + fbaBox.getCode() + "]单据信息，post条件：" + JSON.toJSONString(params), "", 0, "修改货件updateInboundShipment成功");

                    body = new InboundShipmentRequest();

                    //查询网店信息
                    amazonShop = amazonShopMapper.findAmazonShopByGuid(fbaBox.getSellerId());
                    if (amazonShop != null) {
                        address = new Address();
                        secretsVO = new SellerSecretsVO();
                        getAmazonShop(amazonShop, address, secretsVO);

                        //查询头程货件详情信息
                        params1 = new HashMap<String, Object>();
                        //头程计划单下所有箱子数据
                        params1.put("codeBox1", fbaBox.getCode());
                        fbaBoxDetailList = fbaBoxDetailMapper.findFbaBoxDetail(params1);


                        //判断是否需要更改发货状态
                        if (fbaBox.getIsTracking().equals("否")) {
                            inboundShipmentHeader = new InboundShipmentHeader();
                            inboundShipmentHeader.setShipmentName(fbaBox.getShipmentId() + "-" + fbaBox.getDestinationFulfillmentCenterId());
                            inboundShipmentHeader.setShipFromAddress(address);
                            inboundShipmentHeader.setDestinationFulfillmentCenterId(fbaBox.getDestinationFulfillmentCenterId());
                            inboundShipmentHeader.setShipmentStatus(ShipmentStatus.SHIPPED);
                            inboundShipmentHeader.setLabelPrepPreference(LabelPrepPreference.SELLER_LABEL);
                            inboundShipmentHeader.setIntendedBoxContentsSource(IntendedBoxContentsSource.FEED);

                            inboundShipmentItems = new InboundShipmentItemList();


                            if (fbaBoxDetailList.size() != 0) {
                                //将相同的sku、Asin、FnSku相加起来
                                Set<String> fnSkuList = new HashSet<>();
                                List<FbaBoxDetail> fbaBoxDetailListOld = new ArrayList<>();
                                for (FbaBoxDetail fbaBoxDetail : fbaBoxDetailList) {
                                    fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetail.getProductInfo(), FbaBoxDetail.class);
                                    for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailListNew) {
                                        fnSkuList.add(fbaBoxDetai.getFnsku());
                                        fbaBoxDetailListOld.add(fbaBoxDetai);
                                    }
                                }

                                List<FbaBoxDetail> fbaBoxDetailListApi;
                                BigDecimal numPlanDeliver;
                                for (String fnSku : fnSkuList) {
                                    fbaBoxDetailListApi = fbaBoxDetailListOld.stream().filter(
                                            fbaBoxDetail1 -> fbaBoxDetail1.getFnsku().equals(fnSku)
                                    ).collect(Collectors.toList());
                                    numPlanDeliver = BigDecimal.ZERO;
                                    for (FbaBoxDetail fbaBoxDetail : fbaBoxDetailListApi) {
                                        numPlanDeliver = numPlanDeliver.add(new BigDecimal(fbaBoxDetail.getNumRealityDeliver().equals("") ? "0" : fbaBoxDetail.getNumRealityDeliver()));
                                    }
                                    inboundShipmentItem = new InboundShipmentItem();
                                    inboundShipmentItem.setSellerSKU(fbaBoxDetailListApi.get(0).getSku());
                                    inboundShipmentItem.setFulfillmentNetworkSKU(fbaBoxDetailListApi.get(0).getFnsku());
                                    inboundShipmentItem.setQuantityShipped(Integer.valueOf(numPlanDeliver.toString()));
                                    inboundShipmentItems.add(inboundShipmentItem);
                                }
                            }

                            body.setInboundShipmentHeader(inboundShipmentHeader);
                            body.setInboundShipmentItems(inboundShipmentItems);
                            body.setMarketplaceId(amazonShop.getMarketplaceIds());
                            api = Helper.buildApi(secretsVO, FbaInboundApi.class);
                            response = api.updateInboundShipment(body, fbaBox.getShipmentId());

                            fbaBox.setIsTracking("是");
                            fbaBox.setTrackingTime(new Date());
                            fbaBoxMapper.updateByGuid(fbaBox);

                            if (params.get("type").equals("0")) {
                                fbaLogsticsOrderDetailListNew = fbaLogsticsOrderDetailList.stream().filter(
                                        fbaLogsticsOrderDetail -> fbaLogsticsOrderDetail.getShipmentId().equals(fbaBox.getShipmentId())
                                ).collect(Collectors.toList());
                                if (fbaLogsticsOrderDetailListNew.size() != 0) {
                                    fbaLogsticsOrderDetailListNew.get(0).setIsTracking("是");
                                    fbaLogsticsOrderDetailListNew.get(0).setTrackingTime(new Date());
                                }
                            }
                        }

                        //查询详情数据
                        params2 = new HashMap<String, Object>();
                        params2.put("codeShipment", fbaBox.getCodeShipment());
                        params2.put("num", "1");
                        fbaBoxDetails = fbaBoxDetailService.queryAutoList(params2);

                        if (params.get("type").equals("0")) {
                            fbaLogsticsOrderDetailMapper.batchUpdate(fbaLogsticsOrderDetailList);
                        }

                        try {
                            //根据数据生成表格
                            if (amazonShop.getRegionName().equals("欧洲")) {
                                file = new File(ApiConfig.getUploadExcel() + "/poitest1.xlsx");
                            } else {
                                file = new File(ApiConfig.getUploadExcel() + "/poitest2.xlsx");
                            }
                            input = new FileInputStream(file);
                            // HSSFWorkbook用于操作后缀为.xls的excel表格，XSSFWorkbook用于操作.xlsx的excel表格
                            workbook = new HSSFWorkbook(input);
                            // 获取工作簿的方法有两种，一种是根据索引获取，第一个sheet的索引为0，还有一种是根据sheet名称获取
                            sheet = workbook.getSheetAt(0);
                            // 最后一行行号等于sheet的数据行数
                            for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
                                // 得到每一行
                                row = sheet.getRow(i);
                                //排除空白行
                                if (row == null && i == 2) {
                                    continue;
                                }
                                if (i == 0) {
                                    cell = row.getCell(1);
                                    cell.setCellValue(fbaBox.getShipmentId());
                                } else if (i == 3) {
                                    for (int j = 0; j < fbaBox.getNumBox(); j++) {
                                        cell = row.createCell(10 + j);
                                        cell.setCellValue("Box " + (j + 1) + " - QTY");
                                    }
                                } else if (fbaBoxDetails.size() > 0 && i > 3 && i < 62) {
                                    for (int k = 0; k < fbaBoxDetails.size() - 4; k++) {
                                        fbaBoxDetailNew = fbaBoxDetails.get(k);
                                        if (i == 4 + k) {
                                            cell = row.createCell(0);
                                            cell.setCellValue(fbaBoxDetailNew.getSku());
                                            cell = row.createCell(3);
                                            cell.setCellValue(fbaBoxDetailNew.getFnsku());
                                            cell = row.createCell(8);
                                            cell.setCellValue(new Double(fbaBoxDetailNew.getNumPlanDeliver()));
                                            cell = row.createCell(9);
                                            cell.setCellValue(new Double(fbaBoxDetailNew.getNumPlanDeliver()));

                                            addBox(fbaBoxDetailNew, cell, row, amazonShop);
                                        }
                                    }
                                } else if (i == 62) {
                                    for (int j = 0; j < fbaBox.getNumBox(); j++) {
                                        cell = row.createCell(10 + j);
                                        cell.setCellValue("Box " + (j + 1));
                                    }
                                } else if (i == 63) {
                                    fbaBoxDetailNew = fbaBoxDetails.get(fbaBoxDetails.size() - 4);
                                    addBox(fbaBoxDetailNew, cell, row, amazonShop);
                                } else if (i == 64) {
                                    fbaBoxDetailNew = fbaBoxDetails.get(fbaBoxDetails.size() - 3);
                                    addBox(fbaBoxDetailNew, cell, row, amazonShop);
                                } else if (i == 65) {
                                    fbaBoxDetailNew = fbaBoxDetails.get(fbaBoxDetails.size() - 2);
                                    addBox(fbaBoxDetailNew, cell, row, amazonShop);
                                } else if (i == 66) {
                                    fbaBoxDetailNew = fbaBoxDetails.get(fbaBoxDetails.size() - 1);
                                    addBox(fbaBoxDetailNew, cell, row, amazonShop);
                                }
                            }
                            sheet.shiftRows(61, 67, -(67 - 10 - (fbaBoxDetails.size() - 4)));
                            out = new FileOutputStream(ApiConfig.getUploadExcel() + "/" + fbaBox.getShipmentId() + ".xlsx");
                            workbook.write(out);
                            out.close();
                            // 关闭资源
                            workbook.close();
                        } catch (Exception e) {
                            apiResponse.setMsg(fbaBox.getCode() + "生成Excel表格失败!");
                            apiResponse.setCode(400);
                            apiLogService.updateApiLog(insertLogId, "Amazon", "UpdateFbaInbound", "queryParams：" + JSON.toJSONString(fbaBox), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                        }
                        nonPartneredSmallParcelPackageInputs = new NonPartneredSmallParcelPackageInputList();
                        nonPartneredSmallParcelDataInput = new NonPartneredSmallParcelDataInput();
                        nonPartneredSmallParcelDataInput.setCarrierName("other");
                        nonPartneredSmallParcelDataInput.setPackageList(nonPartneredSmallParcelPackageInputs);
                        for (int i = 0; i < fbaBoxDetailList.size(); i++) {
                            nonPartneredSmallParcelPackageInput = new NonPartneredSmallParcelPackageInput();
                            nonPartneredSmallParcelPackageInput.setTrackingId(fbaBoxDetailList.get(i).getTrackingCode());
                            nonPartneredSmallParcelPackageInputs.add(nonPartneredSmallParcelPackageInput);
                        }
                        transportDetailInput = new TransportDetailInput();
                        transportDetailInput.setNonPartneredSmallParcelData(nonPartneredSmallParcelDataInput);

                        putTransportDetailsRequest = new PutTransportDetailsRequest();
                        putTransportDetailsRequest.setIsPartnered(false);
                        putTransportDetailsRequest.setShipmentType(ShipmentType.SP);
                        putTransportDetailsRequest.setTransportDetails(transportDetailInput);

                        api = Helper.buildApi(secretsVO, FbaInboundApi.class);
                        putTransportDetailsResponse = api.putTransportDetails(fbaBox.getShipmentId(), putTransportDetailsRequest);
                        apiLogService.addApiLog("api", "CancelParcel", "putTransportDetailsRequest：" + putTransportDetailsRequest.toString() + "," + "response:" + putTransportDetailsResponse.getPayload(), "", 0, "更新物流信息putTransportDetails成功!");

                        if (putTransportDetailsResponse.getErrors() == null) {
                            String contentType = "application/vnd.ms-excel";
                            CreateFeedDocumentSpecification createFeedDocumentSpecification = new CreateFeedDocumentSpecification();
                            createFeedDocumentSpecification.setContentType(contentType);
                            feedsApi = Helper.buildApi(secretsVO, FeedsApi.class);
                            CreateFeedDocumentResponse createFeedDocumentResponse = feedsApi.createFeedDocument(createFeedDocumentSpecification);
                            String feedDocumentId = createFeedDocumentResponse.getFeedDocumentId();
                            String url = createFeedDocumentResponse.getUrl();

                            String filePath = ApiConfig.getUploadExcel() + "/" + fbaBox.getShipmentId() + ".xlsx";
                            byte[] source = null;
                            try {
                                source = Files.readAllBytes(Paths.get(filePath));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            if (source == null) {
                                apiResponse.setMsg("文件读取错误");
                                apiResponse.setCode(400);
                            }
                            upload(source, url, contentType, 0, fbaBox, fbaBoxDetails);
                            CreateFeedSpecification createFeedSpecification = new CreateFeedSpecification();
                            createFeedSpecification.setFeedType("POST_FLAT_FILE_FROM_EXCEL_FBA_CREATE_CARTON_INFO");
                            createFeedSpecification.setMarketplaceIds(Collections.singletonList(amazonShop.getMarketplaceIds()));
                            createFeedSpecification.setInputFeedDocumentId(feedDocumentId);
                            CreateFeedResponse createFeedResponse = feedsApi.createFeed(createFeedSpecification);
                            String feedId = createFeedResponse.getFeedId();
                            Feed feed;
                            while (true) {
                                feed = feedsApi.getFeed(feedId);
                                if (feed.getProcessingStatus() != Feed.ProcessingStatusEnum.DONE) {
                                    try {
                                        TimeUnit.SECONDS.sleep(2);
                                    } catch (InterruptedException ignored) {
                                        apiResponse.setMsg("访问feed失败!");
                                        apiResponse.setCode(400);
                                    }
                                } else {
                                    break;
                                }
                            }
                            String resultFeedDocumentId = feed.getResultFeedDocumentId();
                            FeedDocument feedDocument = feedsApi.getFeedDocument(resultFeedDocumentId);
                            System.out.println(feedDocument);
                            Boolean upload = upload(source, feedDocument.getUrl(), contentType, 1, fbaBox, fbaBoxDetails);
                            Path path2 = Paths.get(filePath);
                            Files.delete(path2);
                            if (upload == false) {
                                apiResponse.setCode(500);
                                apiResponse.setMsg("上传箱子数据失败!");
                            }

                        }
                    } else {
                        apiResponse.setMsg(fbaBox.getCode() + "头程单名下的店铺不存在!");
                        apiResponse.setCode(400);
                        apiLogService.updateApiLog(insertLogId, "Amazon", "UpdateFbaInbound", "queryParams：" + JSON.toJSONString(fbaBox), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                    }
                    apiResponse.setCode(0);
                    apiResponse.setMsg("上传头程追踪编号成功!");
                } catch (ApiException e) {
                    apiResponse.setCode(400);
                    apiResponse.setMsg("定时修改头程线上发货状态出错，具体错误信息为：" + e.getResponseBody());
                    apiLogService.updateApiLog(insertLogId, "Amazon", "UpdateFbaInbound", "queryParams：" + JSON.toJSONString(fbaBox), JSON.toJSONString(apiResponse), apiResponse.getCode(), apiResponse.getMessage());
                    logger.error("定时修改头程线上发货状态出错，错误信息为：" + e.getMessage());
                }
            }
        }
        return apiResponse;
    }


    /**
     * 海外尾程单审核
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse updateStateName(Map<String, Object> params) throws Exception {
        ApiResponse apiResponse = new ApiResponse();
        Map<String, Object> params1 = new HashMap<String, Object>();
        HwTailprogramApi hwTailprogram1;
        UserInfo userInfo;
        List<HwTailprogram> hwTailprogramList = JSON.parseArray(params.get("infoItems").toString(), HwTailprogram.class);
        for (HwTailprogram hwTailprogram : hwTailprogramList) {
            params1.put("guid", hwTailprogram.getGuid());
            hwTailprogram1 = hwTailprogramMapper.selectFirstRecordByNid(params1);
            if (hwTailprogram1 == null) {
                apiResponse.setCode(400);
                apiResponse.setMsg("尾程单不存在,请核实后在操作!");
                return apiResponse;
            }

            //判断是否需要登录
            if (redisUtil.get("FROESTLOGIN") == null) {
                JSONObject jsonObject = FroestHttPUtils.froestLogin();
                if (jsonObject.get("code") != null) {
                    if (!jsonObject.get("code").equals("200")) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        apiResponse.setCode(400);
                        apiResponse.setMsg("连接大森林海外仓API失败,请联系管理员处理!");
                        return apiResponse;
                    }
                }
                redisUtil.setEx("FROESTLOGIN", jsonObject.get("access_token").toString(), Long.valueOf(jsonObject.get("expires_in").toString()), TimeUnit.SECONDS);
                redisUtil.setEx("FROESTLOGINCode", jsonObject.get("customerCode").toString(), Long.valueOf(jsonObject.get("expires_in").toString()), TimeUnit.SECONDS);
            }

            //0.审核 |1回退
            if (params.get("num").equals("0")) {
                if (hwTailprogram1.getTailprogram() == null) {
                    apiResponse.setCode(400);
                    apiResponse.setMsg("选择单据中未选择尾程方式,请核实后在操作!");
                    return apiResponse;
                }
                if (hwTailprogram1.getChannelcode() == null) {
                    apiResponse.setCode(400);
                    apiResponse.setMsg("选择单据中未选择渠道代码,请核实后在操作!");
                    return apiResponse;
                }
                hwTailprogram1.setStateName(TailprogramEnum.StateName.SUCCESS.value);
                hwTailprogram1.setUpdatetime(new Date());

                //查询仓库编码
                SysDepotInfo sysDepotInfo = sysDepotInfoMapper.findDepotInfoByDepotName(hwTailprogram1.getLaunchwarehouse());
                if (sysDepotInfo == null) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    apiResponse.setCode(400);
                    apiResponse.setMsg("仓库信息不存在,请核实后再操作!");
                }

                List<HwOutboundOrder> hwOutboundOrderList = new ArrayList<>();
                HwOutboundOrder hwOutboundOrder = new HwOutboundOrder();
                hwOutboundOrder.setWarehouseCode(sysDepotInfo.getDepotId());
                hwOutboundOrder.setAddressOne(hwTailprogram1.getAddressline1());
                hwOutboundOrder.setAmazonNumber(hwTailprogram1.getShipmentid());
                hwOutboundOrder.setAmazonReferenceNumber(hwTailprogram1.getHjTrackingCode());
                hwOutboundOrder.setCityId(hwTailprogram1.getCity());
                hwOutboundOrder.setCountryId(hwTailprogram1.getCountrycode());
                hwOutboundOrder.setFbaCode(hwTailprogram1.getDestinationfulfillmentcenterid());
                hwOutboundOrder.setPhone("1234567890");
                hwOutboundOrder.setRecipients(hwTailprogram1.getDestinationfulfillmentcenterid());
                hwOutboundOrder.setType(hwTailprogram1.getTailprogramApi());
                hwOutboundOrder.setCustomerNo(hwTailprogram1.getShipmentid());
                //获取渠道代码
                TsChannelcode tsChannelcode = tsChannelcodeMapper.findByCode(hwTailprogram1.getChannelcode());
                if (tsChannelcode == null) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    logger.error("渠道代码未设置");
                    apiResponse.setCode(400);
                    apiResponse.setMsg("渠道代码未设置,请联系管理员处理!");
                }
                hwOutboundOrder.setDeliveryCode(tsChannelcode.getChannelvalue());
                //查询亚马逊仓库地址
                AmazonAddress amazonAddress = amazonAddressMapper.queryFirstByName(hwTailprogram1.getDestinationfulfillmentcenterid());
                if (amazonAddress == null) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    logger.error("亚马逊地址未设置");
                    apiResponse.setCode(400);
                    apiResponse.setMsg("亚马逊地址未设置,请联系管理员处理!");
                }
                hwOutboundOrder.setZip(amazonAddress.getPostalCode());

                //获取文件数据
                List<String> fileList = new ArrayList<>();
                //查询尾程单详情数据
                Map<String, Object> params2 = new HashMap<String, Object>();
                params2.put("tpcode", hwTailprogram1.getBid());
                List<HwTailprogramdetail> hwTailprogramdetaiList = hwTailprogramdetailMapper.findHwTailprogramdetail(params2);
                List<HwFbaSkuList> hwFbaSkuListList = new ArrayList<>();
                HwFbaSkuList hwFbaSkuList;
                List<HwTailprogramdetail> hwTailprogramdetailNew = null;
                int i = 0;
                for (HwTailprogramdetail hwTailprogramdetail : hwTailprogramdetaiList) {
                    i++;
                    hwTailprogramdetailNew = JSON.parseArray(hwTailprogramdetail.getProductinfo(), HwTailprogramdetail.class);
                    for (HwTailprogramdetail hwTailprogramdetaiNew : hwTailprogramdetailNew) {
                        //修改海外库存数量
                        if (!hwTailprogram.getLaunchwarehouse().equals("福州仓")){
                            HwStorage hwStorage = hwStorageMapper.getKcId(hwTailprogramdetaiNew.getGuidKc());
                            hwStorage.setUpdatetime(new Date());
                            hwStorage.setProductnum(hwStorage.getProductnum() - new Integer(hwTailprogramdetaiNew.getNumRealityDeliver()));
                            hwStorage.setProductnumall(hwStorage.getProductnumall() - new Integer(hwTailprogramdetaiNew.getNumRealityDeliver()));
                            hwStorageMapper.update(hwStorage);
                        }
                        hwFbaSkuList = new HwFbaSkuList();
                        hwFbaSkuList.setAmount(hwTailprogramdetaiNew.getNumRealityDeliver());
                        hwFbaSkuList.setSku(redisUtil.get("FROESTLOGINCode") + "-" + hwTailprogramdetaiNew.getCommodityCode());
                        if (hwTailprogram1.getTailprogramApi().equals("2")) {
                            hwFbaSkuList.setNo(String.valueOf(hwTailprogramdetail.getBoxindex() + 1));
                        }
                        hwFbaSkuListList.add(hwFbaSkuList);

                        if (i == 1){
                            // 商品标
                            String goodsPdf = productBasisService.createGoodsPdf(hwTailprogramdetaiNew.getCommodityCode(), hwTailprogramdetaiNew.getName(), Integer.valueOf(hwTailprogramdetaiNew.getNumPlanDeliver()));

                            fileList.add(goodsPdf);
                        }
                    }
                }
                if (hwTailprogram1.getTailprogramApi().equals("2")) {
                    hwOutboundOrder.setFbaSkuList(hwFbaSkuListList);
                } else {
                    hwOutboundOrder.setHolesaleSkuList(hwFbaSkuListList);
                }
                hwOutboundOrderList.add(hwOutboundOrder);

                Address address;
                SellerSecretsVO secretsVO;
                FbaInboundApi api;
                FbaBox fbaBox;
                //获取fba标
                fbaBox = fbaBoxMapper.queryFirstByCode(hwTailprogram1.getCodebox());
                if (fbaBox == null) {
                    apiResponse.setMsg(fbaBox.getCode() + "头程装箱单不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                userInfo = userInfoMapper.findByUserId(params.get("userId").toString());
                if (userInfo == null){
                    apiResponse.setMsg("用户不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                //查询网店信息
                AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid(fbaBox.getSellerId());
                if (amazonShop != null) {
                    //新增FBA入仓单
                    apiResponse = addFbaWarehousing(fbaBox, userInfo, apiResponse,hwTailprogramdetaiList,amazonShop);
                    if (apiResponse.getCode()  == 400){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }

                    address = new Address();
                    secretsVO = new SellerSecretsVO();
                    getAmazonShop(amazonShop, address, secretsVO);
                    List<String> packageLabelsToPrint = Arrays.asList("1");
                    api = Helper.buildApi(secretsVO, FbaInboundApi.class);
                    GetLabelsResponse response = null;
                    try {
                        response =
                                api.getLabels(fbaBox.getShipmentId(),
                                        "PackageLabel_Plain_Paper",
                                        "BARCODE_2D",
                                        null,
                                        packageLabelsToPrint,
                                        null,
                                        fbaBox.getNumBox(), 0);
                    } catch (ApiException e) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        apiResponse.setMsg(fbaBox.getCode() + "获取透明标失败!");
                        apiResponse.setCode(400);
                        return apiResponse;
                    }
                    apiResponse = addFile(response.getPayload().getDownloadURL(), fileList, apiResponse, 1);
                    if (apiResponse.getCode() == 400) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                } else {
                    apiResponse.setMsg(fbaBox.getCode() + "头程单名下的店铺不存在!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
                //获取透明标
                List<String> listFbaPlanOrderDetail = fbaPlanOrderDetailMapper.queryListFilePath(fbaBox.getCodePlan());
                for (String filePath : listFbaPlanOrderDetail) {
                    apiResponse = addFile(filePath, fileList, apiResponse, 2);
                    if (apiResponse.getCode() == 400) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                }

                //创建大森林出库单
                JSONObject jsonObject = FroestHttPUtils.createOutboundOrder(JSON.toJSONString(hwOutboundOrderList), redisUtil.get("FROESTLOGIN"),
                        "/interface/wmsOrderApi/createOutboundOrder", fileList);
                if (jsonObject.get("code") != null) {
                    if (!jsonObject.get("code").equals(200)) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        logger.error("大森林海外仓API创建出库单失败，错误为：" + jsonObject.get("message"));
                        apiResponse.setCode(400);
                        apiResponse.setMsg("大森林海外仓API创建出库单失败,请联系管理员处理!");
                        return apiResponse;
                    }
                }
                JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("result").toString());
                hwTailprogram1.setStockOutCode(String.valueOf(jsonArray.get(0)));
            }else {
                if (!hwTailprogram1.getStateName().equals(TailprogramEnum.StateName.SUCCESS.value)) {
                    apiResponse.setCode(400);
                    apiResponse.setMsg("选择单据中状态只允许是已审核,请核实后在操作!");
                    return apiResponse;
                }
                hwTailprogram1.setStateName(TailprogramEnum.StateName.INIT.value);
                hwTailprogram1.setUpdatetime(null);

                //查询尾程单详情数据
                Map<String, Object> params2 = new HashMap<String, Object>();
                params2.put("tpcode", hwTailprogram1.getBid());
                List<HwTailprogramdetail> hwTailprogramdetaiList = hwTailprogramdetailMapper.findHwTailprogramdetail(params2);
                List<HwTailprogramdetail> hwTailprogramdetailNew = null;
                for (HwTailprogramdetail hwTailprogramdetail : hwTailprogramdetaiList) {
                    hwTailprogramdetailNew = JSON.parseArray(hwTailprogramdetail.getProductinfo(), HwTailprogramdetail.class);
                    for (HwTailprogramdetail hwTailprogramdetaiNew : hwTailprogramdetailNew) {
                        //修改海外库存数量
                        if (!hwTailprogram.getLaunchwarehouse().equals("福州仓")){
                            HwStorage hwStorage = hwStorageMapper.getKcId(hwTailprogramdetaiNew.getGuidKc());
                            hwStorage.setUpdatetime(new Date());
                            hwStorage.setProductnum(hwStorage.getProductnum() + new Integer(hwTailprogramdetaiNew.getNumRealityDeliver()));
                            hwStorage.setProductnumall(hwStorage.getProductnumall() + new Integer(hwTailprogramdetaiNew.getNumRealityDeliver()));
                            hwStorageMapper.update(hwStorage);
                        }
                    }
                }

                //删除入仓单和详情
                FbaWarehousing fbaWarehousing = fbaWarehousingMapper.queryByCodeBox(hwTailprogram1.getCodebox());
                fbaWarehousingMapper.deleteCodeBox(fbaWarehousing.getCodeBox());

                fbaWarehousingDetailMapper.deleteCode(fbaWarehousing.getBid());

                //取消大森林出库单
                JSONObject jsonObject = FroestHttPUtils.froestApiRequest("",redisUtil.get("FROESTLOGIN"),
                        ApiConfig.getWmsUrl()+"/interface/wmsOrderApi/cancelOutboundOrder?outboundDeliveryNo="+hwTailprogram1.getStockOutCode());
                if (jsonObject.get("code") != null){
                    if (!jsonObject.get("code").equals(200)){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        logger.error("大森林海外仓API取消出库单失败，错误为：" + jsonObject.get("message"));
                        apiResponse.setCode(400);
                        apiResponse.setMsg("大森林海外仓API取消出库单失败,请联系管理员处理!");
                    }
                }
                hwTailprogram1.setStockOutCode(" ");
            }
            hwTailprogramMapper.update(hwTailprogram1);
        }
        apiResponse.setMsg("操作成功!");
        apiResponse.setCode(0);
        return apiResponse;
    }



    @Override
    public ApiResponse getTransportDetails(FbaWarehousing fbaWarehousing,ApiResponse apiResponse) {
        AmazonShop amazonShop = amazonShopMapper.findAmazonShopByGuid(fbaWarehousing.getSellerId());
        if (amazonShop != null) {
            Address address = new Address();
            SellerSecretsVO secretsVO = new SellerSecretsVO();
            getAmazonShop(amazonShop, address, secretsVO);
            FbaInboundApi api = Helper.buildApi(secretsVO, FbaInboundApi.class);
            List<String> shipmentIdList = new ArrayList<>();
            shipmentIdList.add(fbaWarehousing.getShipmentId());
            try {
                GetShipmentsResponse getShipmentsResponse = api.getShipments("SHIPMENT", amazonShop.getSellerId(), null, shipmentIdList, null, null, null);
                InboundShipmentList shipmentData = getShipmentsResponse.getPayload().getShipmentData();
                for (InboundShipmentInfo inboundShipmentInfo : shipmentData){
                    //已发货
                    if (inboundShipmentInfo.getShipmentStatus().getValue().equals("SHIPPED")) {
                        //当前状态不是已发货更新编码
                        try {
                            GetTransportDetailsResponse transportDetails = api.getTransportDetails(fbaWarehousing.getShipmentId());
                            GetTransportDetailsResult getTransportDetailsResult = transportDetails.getPayload();
                            if (getTransportDetailsResult != null) {
                                TransportContent transportContent = getTransportDetailsResult.getTransportContent();
                                if (transportContent != null) {
                                    TransportDetailOutput transportDetails1 = transportContent.getTransportDetails();
                                    if (transportDetails1 != null) {
                                        NonPartneredSmallParcelDataOutput nonPartneredSmallParcelData = transportDetails1.getNonPartneredSmallParcelData();
                                        if (nonPartneredSmallParcelData != null) {
                                            NonPartneredSmallParcelPackageOutputList packageList = nonPartneredSmallParcelData.getPackageList();
                                            if (packageList != null) {
                                                //查询入仓单详情
                                                List<FbaWarehousingDetail> fbaWarehousingDetailList = fbaWarehousingDetailMapper.queryByCode(fbaWarehousing.getBid());
                                                if (packageList.size() == fbaWarehousingDetailList.size()) {
                                                    for (int i = 0; i < packageList.size(); i++) {
                                                        fbaWarehousingDetailList.get(i).setTrackingCode(packageList.get(i).getTrackingId());
                                                        fbaWarehousingDetailMapper.updateByGuid(fbaWarehousingDetailList.get(i));
                                                        //已发货
                                                        fbaWarehousing.setStateName("已发货");
                                                        fbaWarehousingMapper.update(fbaWarehousing);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } catch (ApiException e) {
                            logger.error("获取getTransportDetails失败，错误为：" + e.getResponseBody());
                            apiResponse.setCode(400);
                            apiResponse.setMsg("获取getTransportDetails失败，错误为：" + e.getResponseBody());
                            return apiResponse;
                        }
                    }
                    //已接受和已完成处理数量
                    if (inboundShipmentInfo.getShipmentStatus().getValue().equals("CLOSED") || inboundShipmentInfo.getShipmentStatus().getValue().equals("RECEIVING")){
                        GetShipmentItemsResponse response = api.getShipmentItemsByShipmentId(fbaWarehousing.getShipmentId(), amazonShop.getSellerId());
                        GetShipmentItemsResult payload = response.getPayload();
                        if (payload != null){
                            InboundShipmentItemList itemData = payload.getItemData();
                            if (itemData != null){
                                List<FbaWarehousingDetail> fbaWarehousingDetailNew = null;
                                List<FbaWarehousingDetail> fbaWarehousingDetailList = fbaWarehousingDetailMapper.queryByCode(fbaWarehousing.getBid());
                                for(InboundShipmentItem inboundShipmentItem : itemData){
                                    for (int j = 0; j < fbaWarehousingDetailList.size(); j++) {
                                        fbaWarehousingDetailNew = JSON.parseArray(fbaWarehousingDetailList.get(j).getProductInfo(), FbaWarehousingDetail.class);
                                        for (FbaWarehousingDetail fbaWarehousingDetai1 : fbaWarehousingDetailNew){
                                            if (inboundShipmentItem.getSellerSKU().equals(fbaWarehousingDetai1.getSku())){
                                                fbaWarehousingDetai1.setFbaWarehousingNum(String.valueOf(inboundShipmentItem.getQuantityReceived()));
                                            }
                                        }
                                        fbaWarehousingDetailList.get(j).setProductInfo(JSONArray.toJSONString(fbaWarehousingDetailNew));
                                    }
                                }
                                for (int j = 0; j < fbaWarehousingDetailList.size(); j++) {
                                    fbaWarehousingDetailMapper.updateByGuid(fbaWarehousingDetailList.get(j));
                                }
                                if (inboundShipmentInfo.getShipmentStatus().getValue().equals("RECEIVING")){
                                    //正在接收
                                    fbaWarehousing.setStateName("正在接收");
                                }else {
                                    //已完成
                                    fbaWarehousing.setStateName("已完成");
                                }
                                fbaWarehousingMapper.update(fbaWarehousing);
                            }
                        }
                    }
                }

            } catch (ApiException e) {
                logger.error("获取getTransportDetails失败，错误为：" + e.getResponseBody());
                apiResponse.setCode(400);
                apiResponse.setMsg("获取getTransportDetails失败，错误为：" + e.getResponseBody());
            }
        }
        return apiResponse;
    }

    private ApiResponse addFile(String dowUrl,List<String> fileList,ApiResponse apiResponse,int type){
        try {
            URL url = new URL(dowUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            // 防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            // 得到输入流
            InputStream inputStream = conn.getInputStream();

            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();
            // 获取字节数组
            byte[] getData = bos.toByteArray();

            // 文件保存位置
            File saveDir = new File(Global.getProfile());
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            String pdfFileName = "";
            if (type == 1){
                pdfFileName = "/FBA箱标.pdf";
            }else  if (type == 2){
                pdfFileName = "/透明标.pdf";
            }else {
                pdfFileName = "/商品标.pdf";
            }
            File file = new File(saveDir + pdfFileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            fileList.add(saveDir + pdfFileName);
        } catch (Exception e) {
            apiResponse.setMsg("文件下载失败!");
            apiResponse.setCode(400);
            return apiResponse;
        }
        return apiResponse;
    }

    /**
     *
     * @param logisticsAccount 转入公司账号
     * @param operationAccount 转出公司账号
     * @param userInfo
     */
    private void addAccountDetailedForCompany(
            AccountCountForCompany logisticsAccount, AccountCountForCompany operationAccount,
            UserInfo userInfo,
            Double priceTranPredict,String vBz,String vJyLx
            ,String mname,int mType,String mNid,String mBid,String mGuid,Date dJySj,List<AccountDetailedForCompany> accountList){
        AccountDetailedForCompany account = new AccountDetailedForCompany();
        account.setGuid(RandomValueUtils.getGUID());
        account.setvGsBm(operationAccount.getvGsBm());
        account.setvGsMc(operationAccount.getvGsMc());
        account.setvGsJc(operationAccount.getvGsJc());
        account.setvGsBmP(logisticsAccount.getvGsBm());
        account.setvGsMcP(logisticsAccount.getvGsMc());
        account.setvGsJcP(logisticsAccount.getvGsJc());
        account.setvJyLx(vJyLx);
        account.setfJe(priceTranPredict);
        account.setdJySj(dJySj);
        account.setdShSj(new Date());
        account.setvBz(vBz);
        account.setCreateTime(new Date());
        account.setmName(mname);
        account.setmType(mType);
        account.setmNid(mNid);
        account.setmBid(mBid);
        account.setmGuid(mGuid);
        accountList.add(account);
    }

    public void addUpdateLog(String moduleTable,String targetGuid,Object oldBean, Object newBean, String operatorName,UserInfo userInfo) {
        UpdateLog updateLog = new UpdateLog();
        String AlterTheContent = BeanLogUtils.getChangedFields(oldBean,newBean);
        updateLog.setGuid(RandomValueUtils.getGUID());
        updateLog.setUserId(userInfo.getUserId());
        updateLog.setCreateTime(new Date());
        updateLog.setActionType(operatorName);
        updateLog.setModuleTable(moduleTable);
        updateLog.setModuleGuid(targetGuid);
        updateLog.setAlterTheContent(AlterTheContent);
        if (AlterTheContent.length() > 0){
            updateLogMapper.insert(updateLog);
        }
    }

    private void addDevanningDetail(FbaBoxDetail fbaBoxDetai,FbaDevanningDetail fbaDevanningDetail,FbaDevanning fbaDevanning,UserInfo userInfo,ApiResponse apiResponse,int type){
        try {
            fbaDevanningDetail.setGuid(RandomValueUtils.getGUID());
            fbaDevanningDetail.setCodeDevanning(fbaDevanning.getCodeDevanning());
            fbaDevanningDetail.setCommodityCode(fbaBoxDetai.getCommodityCode());
            fbaDevanningDetail.setNameGoodsCn(fbaBoxDetai.getName());
            fbaDevanningDetail.setNumPlanDeliver(fbaBoxDetai.getNumPlanDeliver());
            fbaDevanningDetail.setCreateUser(userInfo.getUserId());
            fbaDevanningDetail.setCreateTime(new Date());
            fbaDevanningDetail.setGuidKc(fbaBoxDetai.getGuidKc());
            fbaDevanningDetail.setvGsBm(fbaBoxDetai.getvGsBm());
            fbaDevanningDetail.setRkGuid(fbaBoxDetai.getRkGuid());
            fbaDevanningDetail.setCodeStockLocation(fbaBoxDetai.getCodeStockLocation());
            fbaDevanningDetail.setCodeStockOn(fbaBoxDetai.getCodeStockOn());
            fbaDevanningDetail.setCodeStockArea(fbaBoxDetai.getCodeStockArea());
            fbaDevanningDetail.setPriceIn(Double.valueOf(fbaBoxDetai.getPriceIn()));
            if (type == 1){
                fbaDevanningDetail.setNumStorage(Integer.parseInt(fbaBoxDetai.getNumPlanDeliver()));
            }
            fbaDevanningDetailMapper.insertFbaDevanningDetail(fbaDevanningDetail);
        }catch (Exception e){
            apiResponse.setMsg("新增拆箱单详情失败!");
            apiResponse.setCode(400);
        }
    }


    private void addFbaBox(FbaShipment fbaShipment,FbaBox fbaBox,UserInfo userInfo,ApiResponse apiResponse){
        try {
            ModuleNidAndBid moduleNidAndBid;
            Map<String, Object> params2;
            //查询头程货件最新数据
            params2 = new HashMap<String, Object>();
            params2.put("moduleTable", "TP_FBABOX");
            moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params2);    //有事务控制，制单异常不跳过单号
            //新增头程装箱单
            fbaBox.setGuid(RandomValueUtils.getGUID());
            fbaBox.setNid(moduleNidAndBid.getNid());
            fbaBox.setBid(moduleNidAndBid.getBid());
            fbaBox.setCid(userInfo.getCid());
            fbaBox.setCidName(userInfo.getCidName());
            fbaBox.setbUser(userInfo.getUserId());
            fbaBox.setbUserName(userInfo.getUserName());
            fbaBox.setbDept(userInfo.getDeptPath());
            fbaBox.setbDeptName(userInfo.getDeptName());
            fbaBox.setbPosition(userInfo.getPositionNameDa());
            fbaBox.setaUser(userInfo.getUserId());
            fbaBox.setaUserName(userInfo.getUserName());
            fbaBox.setaDept(userInfo.getDeptPath());
            fbaBox.setaDeptName(userInfo.getDeptName());
            fbaBox.setaPosition(userInfo.getPositionNameDa());
            fbaBox.setCode(moduleNidAndBid.getBid());
            fbaBox.setState("0");
            fbaBox.setStateName("未装箱");
            fbaBox.setStatePrint("0");
            fbaBox.setStatePrintName("配货清单未打印");
            fbaBox.setStateTrack("0");
            fbaBox.setStateTrackName("无");
            fbaBox.setCodeShipment(fbaShipment.getCode());
            fbaBox.setCreateTime(new Date());
            fbaBox.setCreateUser(userInfo.getUserId());
            fbaBox.setNumBox(0);
            fbaBox.setWeightReal(new BigDecimal(0));
            fbaBox.setWeightVol(new BigDecimal(0));
            fbaBox.setWeightCal(fbaShipment.getWeightCalPredict());
            fbaBox.setDestinationFulfillmentCenterId(fbaShipment.getDestinationFulfillmentCenterId());
            fbaBox.setShipmentId(fbaShipment.getShipmentId());
            fbaBox.setvZdbz(fbaShipment.getvZdbz());
            fbaBox.setPriceTranPredict(fbaShipment.getPriceTranPredict());
            fbaBox.setPriceCalPerKg(fbaShipment.getPriceCalPerKg());
            fbaBox.setPriceTranCalWeightPredict(fbaShipment.getPriceTranCalWeightPredict());
            fbaBox.setPriceQualityExtra(fbaShipment.getPriceQualityExtra());
            fbaBox.setPriceQualityExtraPerKg(fbaShipment.getPriceQualityExtraPerKg());
            fbaBox.setPriceQualityExtraPredict(fbaShipment.getPriceQualityExtraPredict());
            fbaBox.setNumProName(fbaShipment.getNumProName());
            fbaBox.setNumProNameBeyond(fbaShipment.getNumProNameBeyond());
            fbaBox.setPriceProNamePerOne(fbaShipment.getPriceProNamePerOne());
            fbaBox.setPriceProNameExtraPredict(fbaShipment.getPriceProNameExtraPredict());
            fbaBox.setZysx(fbaShipment.getZysx());
            fbaBox.setCodeCompany(fbaShipment.getCodeCompany());
            fbaBox.setNameCompany(fbaShipment.getNameCompany());
            fbaBox.setCodeLogsticsPattern(fbaShipment.getCodeLogsticsPattern());
            fbaBox.setNameLogsticsPattern(fbaShipment.getNameLogsticsPattern());
            fbaBox.setNameLogsticsWay(fbaShipment.getNameLogsticsWay());
            fbaBox.setNameLogsticsClearance(fbaShipment.getNameLogsticsClearance());
            fbaBox.setStateShareTicket(String.valueOf(fbaShipment.getStateShareTicket()));
            fbaBox.setStateShareTicketName(fbaShipment.getStateShareTicket() == 0 ?"否":"是");
            fbaBox.setPriceClearanceOpe(fbaShipment.getPriceClearanceOpe());
            fbaBox.setCoefficientWeight(fbaShipment.getCoefficientWeight());
            fbaBox.setToPurchasePrice(String.valueOf(fbaShipment.getToPurchasePrice()));
            fbaBox.setRealityPurchasePrice("0");
            fbaBox.setPriceSingleBoxReq(fbaShipment.getPriceSingleBoxReq());
            fbaBox.setIsBinning("否");
            fbaBox.setvGsJc(fbaShipment.getvGsJc());
            fbaBox.setSinglePassCrane(fbaShipment.getSinglePassCrane());
            fbaBox.setWeightCalBySingle(fbaShipment.getWeightCalBySingle());
            fbaBox.setJzPrice(fbaShipment.getJzPrice());
            fbaBox.setPzjzPrice(fbaShipment.getPzjzPrice());
            fbaBox.setLogisticsType(fbaShipment.getLogisticsType());
            fbaBox.setTdjzPrice(fbaShipment.getTdjzPrice());
            fbaBox.setJettisonCoe(fbaShipment.getJettisonCoe());
            fbaBox.setSurchargeMaterialMax(fbaShipment.getSurchargeMaterialMax());
            fbaBox.setNameSurchargePrice(fbaShipment.getNameSurchargePrice());
            fbaBox.setPriceClearanceOpePrice(fbaShipment.getPriceClearanceOpePrice());
            fbaBox.setTradeNamePro(fbaShipment.getTradeNamePro());
            fbaBox.setPriceClearanceOpeCs(fbaShipment.getPriceClearanceOpeCs());
            fbaBox.setNumMaxProName(fbaShipment.getNumMaxProName());
            fbaBox.setNumFreeProName(fbaShipment.getNumFreeProName());
            fbaBox.setJettisonWeightCharge(fbaShipment.getJettisonWeightCharge());
            fbaBox.setActualLogisticsFreight(fbaShipment.getPriceTranPredict());
            fbaBox.setLogisticsMmodeGuid(fbaShipment.getLogisticsMmodeGuid());
            fbaBox.setNumFreeProNameNew(fbaShipment.getNumFreeProNameNew());
            fbaBox.setIsTracking("否");
            fbaBox.setWeightCalA1(BigDecimal.ZERO);
            fbaBox.settCNum(0);
            fbaBox.setWarehouseSurchargePrice(BigDecimal.ZERO);
            fbaBox.setWarehouseSurcharge(BigDecimal.ZERO);
            //抛重发货数据
            fbaBox.setLoadDelivery("否");
            fbaBox.setActualLogisticsFreightPf(BigDecimal.ZERO);
            fbaBox.setPriceTranCalWeightPredictPf(BigDecimal.ZERO);
            fbaBox.setPriceQualityExtraPredictPf(BigDecimal.ZERO);
            fbaBox.setPriceProNameExtraPredictPf(BigDecimal.ZERO);
            fbaBox.setPriceClearanceOpePf(BigDecimal.ZERO);
            fbaBox.setNumFreeProNamePf(fbaShipment.getNumFreeProName());
            fbaBox.setPriceSingleBoxReqZd(fbaShipment.getPriceSingleBoxReqZd());
            fbaBoxMapper.insertFbaBox(fbaBox);
        }catch (Exception e){
            apiResponse.setMsg("新增装箱信息失败!");
            apiResponse.setCode(400);
            return;
        }

    }

    /**
     * 判断字符串是否是数字
     * @param num
     * @return
     */
    private int estimateNum(String num){
        if (StringUtils.isNumeric(num)){
            return Integer.parseInt(num);
        } else {
            return 0;
        }
    }

    /**
     * 当亚马逊出现分仓数据进行逻辑操作
     */
    private ApiResponse separateWarehouse(InboundShipmentPlanList inboundShipmentPlans,FbaPlanOrder fbaPlanOrder1,
                                          ApiResponse apiResponse,Address harvestAddress,UserInfo userInfo,
                                          Address address,InboundShipmentRequest inboundShipmentRequest,
                                          InboundShipmentHeader inboundShipmentHeader,InboundShipmentItemList inboundShipmentItems,
                                          InboundShipmentItem inboundShipmentItem,List<FbaPlanOrderDetail> fbaPlanOrderDetailList,
                                          PrepDetailsList prepDetails,AmazonShop  amazonShop,FbaInboundApi api) throws ApiException {
        try {
            Map<String, Object> params11 = new HashMap<String, Object>();
            params11.put("guid",fbaPlanOrder1.getLogisticsMmodeGuid());
            //查询物流方式
            LogisticsMmode logisticsMmode = logsticsMmodeMapper.queryFirstByGuid(params11);
            //获取物流方式详情
            Map<String, Object> params4 = new HashMap<String, Object>();
            params4.put("logisticsMmodeGuid",fbaPlanOrder1.getLogisticsMmodeGuid());
            List<LogisticsMmodeDetails> textureList = logsticsMmodeDetailsMapper.findLogisticsMmodeDetails(params4);
            //获取物流方式梯度
            List<LogisticsMmodeGrads> logisticsMmodeGradList = logsticsMmodeGradsMapper.findLogisticsMmodeGrads(params4);
            List<LogisticsMmodeGrads> logisticsMmodeGrads  = logisticsMmodeGradList.stream().filter(logisticsMmodeGrads1 ->
                    "WLFS".equals(logisticsMmodeGrads1.getType())).collect(Collectors.toList());
            List<LogisticsMmodeGrads> logisticsMmodeInfoItems  = logisticsMmodeGradList.stream().filter(logisticsMmodeGrads1 ->
                    "WLFSTDJZ".equals(logisticsMmodeGrads1.getType())).collect(Collectors.toList());

            params4.remove("logisticsMmodeGuid");
            params4.put("type","WLPMTD");
            //获取品名梯度详情
            List<LogisticsMmodeGrads> wlpmtdList = logsticsMmodeGradsMapper.findLogisticsMmodeGrads(params4);


            List<FbaShipmentDetail> fbaShipmentDetailList;
            FbaShipmentDetail fbaShipmentDetail;
            Set<String> gradeNum;
            BigDecimal weightRealPredict;
            BigDecimal weightVolPredict;
            BigDecimal texture;
            String surchargeMaterialMax;
            BigDecimal weightPrice;
            BigDecimal phweightPrice;
            BigDecimal priceTranCalWeightPredict;
            BigDecimal priceClearanceOpePrice;
            BigDecimal predVal;
            List<LogisticsMmodeGrads> tdjzPrice;
            List<LogisticsMmodeGrads> pzjzPrice;
            List<LogisticsMmodeGrads> phjzPrice;
            List<LogisticsMmodeGrads> qgPrice;
            BigDecimal tradeNamePro;
            BigDecimal weightVolPredictNew;
            BigDecimal weightCalPredict22;
            Boolean numWeightCal;
            BigDecimal weightCalPredict;
            Integer numProName;
            Double numFreeProName;
            Integer num;
            for (InboundShipmentPlan inboundShipmentPlan : inboundShipmentPlans) {
                fbaShipmentDetailList = new ArrayList<>();
                //收货地址信息
                harvestAddress = inboundShipmentPlan.getShipToAddress();

                //新增货件单
                FbaShipment fbaShipment = new FbaShipment();
                ModuleNidAndBid moduleNidAndBid;
                Map<String, Object> params2;
                //查询头程货件最新数据
                params2 = new HashMap<String, Object>();
                params2.put("moduleTable", "TP_FbaShipment");
                moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params2);    //有事务控制，制单异常不跳过单号
                //新增头程货件单
                BeanUtils.copyProperties(fbaPlanOrder1, fbaShipment);
                fbaShipment.setGuid(RandomValueUtils.getGUID());
                fbaShipment.setNid("0");
                fbaShipment.setCode(moduleNidAndBid.getBid());
                fbaShipment.setCreateTime(new Date());
                fbaShipment.setCid(userInfo.getCid());
                fbaShipment.setCidName(userInfo.getCidName());
                fbaShipment.setbUser(userInfo.getUserId());
                fbaShipment.setbUserName(userInfo.getUserName());
                fbaShipment.setbDept(userInfo.getDeptPath());
                fbaShipment.setbDeptName(userInfo.getDeptName());
                fbaShipment.setbPosition(userInfo.getPositionNameDa());
                fbaShipment.setaUser(userInfo.getUserId());
                fbaShipment.setaUserName(userInfo.getUserName());
                fbaShipment.setaDept(userInfo.getDeptPath());
                fbaShipment.setaDeptName(userInfo.getDeptName());
                fbaShipment.setaPosition(userInfo.getPositionNameDa());
                fbaShipment.setCodePlan(fbaPlanOrder1.getCode());
                //设置收货地址
                fbaShipment.setName(harvestAddress.getName());
                fbaShipment.setDistrictOrCounty(harvestAddress.getDistrictOrCounty());
                fbaShipment.setAddressLine1(harvestAddress.getAddressLine1());
                fbaShipment.setAddressLine2(harvestAddress.getAddressLine2());
                fbaShipment.setCity(harvestAddress.getCity());
                fbaShipment.setStateOrProvinceCode(harvestAddress.getStateOrProvinceCode());
                fbaShipment.setCountryCode(harvestAddress.getCountryCode());
                fbaShipment.setPostalCode(harvestAddress.getPostalCode());
                fbaShipment.setDestinationFulfillmentCenterId(inboundShipmentPlan.getDestinationFulfillmentCenterId());
                if ("自动".equals(fbaPlanOrder1.getCreationMethod())) {
                    fbaShipment.setState("0");
                } else {
                    fbaShipment.setState("1");
                }
                fbaShipment.setAuditTime(new Date());
                fbaShipment.setAuditUser(userInfo.getUserId());
                fbaShipment.setShipmentId(inboundShipmentPlan.getShipmentId());
                fbaShipment.setvZdbz(fbaPlanOrder1.getvZdbz());
                fbaShipment.setZysx(fbaPlanOrder1.getZysx());
//            fbaShipment.setPriceClearanceOpe(fbaPlanOrder1.getPriceClearanceOpe());
                fbaShipment.setCoefficientWeight(fbaPlanOrder1.getCoefficientWeight());
                fbaShipment.setToPurchasePrice(fbaPlanOrder1.getToPurchasePrice());
                fbaShipment.setPriceSingleBoxReq(fbaPlanOrder1.getPriceSingleBoxReq());
                fbaShipment.setLogisticsMmodeGuid(fbaPlanOrder1.getLogisticsMmodeGuid());
                fbaShipment.setNumFreeProNameNew(fbaPlanOrder1.getNumFreeProNameNew());
                fbaShipment.setCurrencyAmount(inboundShipmentPlan.getEstimatedBoxContentsFee().getTotalFee().getValue());
                fbaShipment.setCurrency(inboundShipmentPlan.getEstimatedBoxContentsFee().getTotalFee().getCurrencyCode().getValue());


                inboundShipmentRequest = new InboundShipmentRequest();

                inboundShipmentHeader = new InboundShipmentHeader();
                inboundShipmentHeader.setShipmentName(inboundShipmentPlan.getShipmentId() + "-" + inboundShipmentPlan.getDestinationFulfillmentCenterId());
                inboundShipmentHeader.setShipFromAddress(address);
                inboundShipmentHeader.setDestinationFulfillmentCenterId(inboundShipmentPlan.getDestinationFulfillmentCenterId());
                inboundShipmentHeader.setShipmentStatus(ShipmentStatus.WORKING);
                inboundShipmentHeader.setLabelPrepPreference(LabelPrepPreference.SELLER_LABEL);
                inboundShipmentHeader.setIntendedBoxContentsSource(IntendedBoxContentsSource.FEED);

                inboundShipmentItems = new InboundShipmentItemList();


                //品名数量
                gradeNum = new HashSet<>();
                weightRealPredict = BigDecimal.ZERO;
                weightVolPredict = BigDecimal.ZERO;
                //最大的材质值
                texture = BigDecimal.ZERO;
                //最大值材质名称
                surchargeMaterialMax = "";
                //品名判断数值
                numWeightCal = true;
                weightCalPredict = BigDecimal.ZERO;
                priceTranCalWeightPredict = BigDecimal.ZERO;
                //超出品名
                num = 0;
                FbaPlanOrderDetail fbaPlanOrderDetailNew;
                numFreeProName = null;
                Integer quantity = 0;
                //拿到对应的头程计划详情信息
                for (InboundShipmentPlanItem inboundShipmentPlanItem : inboundShipmentPlan.getItems()) {
                    //扣减的数量
                    quantity = inboundShipmentPlanItem.getQuantity();
                    List<FbaPlanOrderDetail> fbaPlanOrderDetailList1  = new ArrayList<>();
                    for (FbaPlanOrderDetail fbaPlanOrderDetail :fbaPlanOrderDetailList){
                        if (inboundShipmentPlanItem.getSellerSKU().equals(fbaPlanOrderDetail.getSku())
                                || inboundShipmentPlanItem.getFulfillmentNetworkSKU().equals(fbaPlanOrderDetail.getFnsku())){
                            //判断数量是否足够
                            if ( fbaPlanOrderDetail.getNumPlanDeliver() != 0){
                                if (fbaPlanOrderDetail.getNumPlanDeliver() > quantity){
                                    fbaPlanOrderDetail.setNumPlanDeliver(fbaPlanOrderDetail.getNumPlanDeliver() - quantity);
                                    fbaPlanOrderDetailNew = new FbaPlanOrderDetail();
                                    BeanUtils.copyProperties(fbaPlanOrderDetail,fbaPlanOrderDetailNew);
                                    fbaPlanOrderDetailNew.setNumPlanDeliver(quantity);
                                    fbaPlanOrderDetailList1.add(fbaPlanOrderDetailNew);
                                    break;
                                }else {
                                    fbaPlanOrderDetailNew = new FbaPlanOrderDetail();
                                    BeanUtils.copyProperties(fbaPlanOrderDetail,fbaPlanOrderDetailNew);
                                    fbaPlanOrderDetailNew.setNumPlanDeliver(fbaPlanOrderDetail.getNumPlanDeliver());
                                    fbaPlanOrderDetailList1.add(fbaPlanOrderDetailNew);
                                    quantity = quantity - fbaPlanOrderDetail.getNumPlanDeliver();
                                    fbaPlanOrderDetail.setNumPlanDeliver(0);
                                }
                            }
                        }
                    }
                    if (fbaPlanOrderDetailList1.size() == 0) {
                        apiResponse.setMsg(fbaPlanOrder1.getCode() + "头程计划名下的商品信息不存在!");
                        apiResponse.setCode(400);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    } else {
                        for (FbaPlanOrderDetail fbaPlanOrderDetail : fbaPlanOrderDetailList1) {
                            //单条数据计算预估重量和抛重
                            fbaPlanOrderDetail.setWeightPredict((new BigDecimal(fbaPlanOrderDetail.getNumPlanDeliver()).multiply(fbaPlanOrderDetail.getWeightPackage())).setScale(2, BigDecimal.ROUND_HALF_UP));
                            fbaPlanOrderDetail.setWeightVolPredict((fbaPlanOrderDetail.getLengthPackage().multiply(fbaPlanOrderDetail.getWidthPackage()).multiply(fbaPlanOrderDetail.getHeightPackage()))
                                    .multiply(new BigDecimal(fbaPlanOrderDetail.getNumPlanDeliver()).divide(new BigDecimal(fbaPlanOrder1.getCoefficientWeight()),2,RoundingMode.HALF_UP)));
                            //新增头程货件详情信息
                            fbaShipmentDetail = new FbaShipmentDetail();
                            BeanUtils.copyProperties(fbaPlanOrderDetail, fbaShipmentDetail);
                            fbaShipmentDetail.setGuid(RandomValueUtils.getGUID());
                            fbaShipmentDetail.setCodeShipmentOrder(fbaShipment.getCode());
                            fbaShipmentDetail.setBUser(userInfo.getUserId());
                            fbaShipmentDetail.setBDept(userInfo.getDeptPath());
                            fbaShipmentDetail.setCreateUser(userInfo.getUserId());
                            fbaShipmentDetail.setCreateTime(new Date());
                            fbaShipmentDetail.setPdGuid(fbaPlanOrderDetail.getGuid());
                            fbaShipmentDetail.setSpGuid(fbaPlanOrderDetail.getSpGuid());
                            fbaShipmentDetail.setIsSign(fbaPlanOrderDetail.getIsSign());
                            fbaShipmentDetailList.add(fbaShipmentDetail);

                            // 总预估实重 = 所有的详情 (组装重量（kg）*计划发货数量 )相加
                            weightRealPredict=weightRealPredict.add(fbaPlanOrderDetail.getWeightPredict());
                            // 总预估抛重 = 所有的详情 (组装长*宽*高/抛货系数*数量/抛货系数)相加
                            weightVolPredict=weightVolPredict.add(fbaPlanOrderDetail.getWeightVolPredict());

                            //不一样的品名数=(商品中文、海关编码、材质中文只要一个不同)
                            String join = fbaPlanOrderDetail.getNameGoodsCn() + '-' + fbaPlanOrderDetail.getCodeGoodsHs() + '-' +fbaPlanOrderDetail.getNameMaterialCn();
                            gradeNum.add(join);
                            //判断是否是混合材质
                            if (fbaPlanOrderDetail.getNameMaterialCn().indexOf(",") == -1) {
                                //赋值材质附加费(取最大值)
                                for (int j = 0; j < textureList.size(); j++) {
                                    if (textureList.get(j).getMaterialName().equals(fbaPlanOrderDetail.getNameMaterialCn())) {
                                        if (textureList.get(j).getMaterialCost().compareTo(texture) > 0) {
                                            texture = (textureList.get(j).getMaterialCost());
                                            surchargeMaterialMax = (textureList.get(j).getMaterialName());
                                        }
                                    }
                                }
                            } else {
                                String[] nameMaterialCnList = fbaPlanOrderDetail.getNameMaterialCn().split(",");
                                for (String nameMaterialCn : nameMaterialCnList) {
                                    for (int j = 0; j < textureList.size(); j++) {
                                        if (textureList.get(j).getMaterialName().equals(nameMaterialCn)) {
                                            if (textureList.get(j).getMaterialCost().compareTo(texture) > 0) {
                                                texture = (textureList.get(j).getMaterialCost());
                                                surchargeMaterialMax = (textureList.get(j).getMaterialName());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    weightPrice = BigDecimal.ZERO;
                    phweightPrice = BigDecimal.ZERO;
                    priceClearanceOpePrice = new BigDecimal(100);
                    predVal = BigDecimal.ZERO;
                    tradeNamePro = BigDecimal.ZERO;
                    weightVolPredictNew = BigDecimal.ZERO;
                    weightCalPredict22 = BigDecimal.ZERO;
                    //实际品名数
                    numProName = 0;

                    //判断是否是拼票
                    if (fbaShipment.getStateShareTicketName().equals('是')){
                        //预估计重=实重进行约分
                        fbaShipment.setWeightRealPredict(weightRealPredict.setScale(2, BigDecimal.ROUND_HALF_UP));
                        fbaShipment.setWeightVolPredict(weightVolPredict.setScale(2, BigDecimal.ROUND_HALF_UP));
                        //预估计重（A1）=MAX（预估实重，预估抛重，单箱起重）然后进行计重约分
                        weightCalPredict22 = weightRealPredict.max(fbaShipment.getWeightCalBySingle());
                        weightCalPredict22 = precision(weightCalPredict22);
                        fbaShipment.setWeightCalPredict(weightCalPredict22);
                        //1.预估计重<单票起重的二分之一,实际品名数=免费品名数/2&向下取整
                        numWeightCal = weightCalPredict22.compareTo(fbaShipment.getSinglePassCrane().divide(new BigDecimal(2)))<0;
                        //实际品名数
                        numProName = gradeNum.size();
                        if (numWeightCal){
                            //实际品名免费数
                            numFreeProName = Math.floor(logisticsMmode.getNumFreeProName()/2);
                        }
                        //2.预估计重>=单票起重的二分之一,实际品名数=免费品名数/2&向上取整
                        if (!numWeightCal && weightCalPredict22.compareTo(fbaShipment.getSinglePassCrane())<0){
                            numFreeProName = Math.ceil(logisticsMmode.getNumFreeProName()/2);
                        }
                        if (weightCalPredict22.compareTo(fbaShipment.getSinglePassCrane()) >= 0){
                            //3.预估计重>=单票起重,实际品名数=免费品名数
                            numFreeProName = logisticsMmode.getNumFreeProName().doubleValue();
//                        numProName = numFreeProName.intValue();
                        }

                        //梯度计重单价=(预估计重满足区间的值)
                        BigDecimal finalWeightCalPredict22 = weightCalPredict22;
                        tdjzPrice = logisticsMmodeGrads.stream().filter(logisticsMmodeGrads1 -> finalWeightCalPredict22.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                                && finalWeightCalPredict22.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
                        //抛重计重单价=(抛重的值-预估计重)
                        predVal = (weightVolPredict.subtract(weightRealPredict)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal finalPredVal = predVal;
                        pzjzPrice = logisticsMmodeInfoItems.stream().filter(logisticsMmodeGrads1 -> finalPredVal.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                                && finalPredVal.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
                        //计重单价=梯度计重单价+抛重计重单价
                        weightPrice = (tdjzPrice.size()!=0?tdjzPrice.get(0).getKg():BigDecimal.ZERO).add(pzjzPrice.size()!=0?pzjzPrice.get(0).getKg():BigDecimal.ZERO);

                        //MAX（预估抛重，单箱起重）（先进行约分）
                        weightVolPredictNew = precision((weightVolPredict.max(fbaShipment.getSinglePassCrane())));

                        //抛重梯度计重单价=梯度计重单价
//                    BigDecimal finalWeightVolPredictNew = weightVolPredictNew;
//                    phjzPrice = logisticsMmodeGrads.stream().filter(logisticsMmodeGrads1 -> finalWeightVolPredictNew.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
//                            && finalWeightVolPredictNew.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
                        phweightPrice = (tdjzPrice.size()!=0?tdjzPrice.get(0).getKg():BigDecimal.ZERO);

                        //抛货计重费=预估抛重*梯度计重单价
                        fbaShipment.setJettisonWeightCharge(weightVolPredictNew.multiply(phweightPrice).setScale(2, BigDecimal.ROUND_HALF_UP));


                        //抛重>实重，预估计重费=MIN(预估计重*计重单价,抛货计重费)；抛重<=实重，预估计重费=预估计重*计重单价；计重单价=梯度计重单价+抛重计重单价
                        priceTranCalWeightPredict = (weightCalPredict22.multiply(weightPrice)).setScale(2, BigDecimal.ROUND_HALF_UP);

                        if (weightVolPredict.compareTo(weightRealPredict) > 0){
                            if (priceTranCalWeightPredict.compareTo(weightVolPredictNew.multiply(phweightPrice))>=0){
                                fbaShipment.setPriceTranCalWeightPredict(fbaShipment.getJettisonWeightCharge());
                            }else {
                                fbaShipment.setPriceTranCalWeightPredict(priceTranCalWeightPredict);
                            }
                        } else {
                            fbaShipment.setPriceTranCalWeightPredict(priceTranCalWeightPredict);
                        }

                        //清关费=清关费*清关占比
                        if (fbaShipment.getNumMaxProName()!= 0){
                            //品名数/上限数
                            tradeNamePro = new BigDecimal(gradeNum.size()).divide(new BigDecimal(logisticsMmode.getNumMaxProName()),2, RoundingMode.HALF_UP);
                            BigDecimal finalTradeNamePro = tradeNamePro;
                            qgPrice = wlpmtdList.stream().filter(logisticsMmodeGrads1 -> finalTradeNamePro.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                                    && finalTradeNamePro.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
                            priceClearanceOpePrice = qgPrice.size()!=0?qgPrice.get(0).getKg():BigDecimal.ZERO;
                        }
                        //占比
                        fbaShipment.setTradeNamePro(priceClearanceOpePrice);
                        //预估清光费(物流方式清光费*品名占比)
                        fbaShipment.setPriceClearanceOpe((logisticsMmode.getPriceClearanceOpe().multiply(priceClearanceOpePrice)).divide(new BigDecimal(100),2,RoundingMode.HALF_UP));
                        //超出品名=实际品名-实际免费品名数
                        num = numProName-numFreeProName.intValue();
                        //品名免费数
                        fbaShipment.setNumFreeProName(numFreeProName.intValue());
                        fbaShipment.setNumProName(numProName);
                    } else {
                        //预估计重=MAX(实重/抛重)
                        weightCalPredict = weightRealPredict.compareTo(weightVolPredict) >0?weightRealPredict:weightVolPredict;
                        fbaShipment.setWeightRealPredict(weightRealPredict.setScale(2, BigDecimal.ROUND_HALF_UP));
                        fbaShipment.setWeightVolPredict(weightVolPredict.setScale(2, BigDecimal.ROUND_HALF_UP));
                        //预估计重（A1）=MAX（预估实重，预估抛重，单箱起重）然后进行计重约分
                        weightCalPredict22 = weightRealPredict.max(fbaShipment.getWeightCalBySingle());
                        weightCalPredict22 = precision((weightCalPredict22.max(weightVolPredict)));
                        //预估计重=MAX（A1，单票起重）
                        weightCalPredict22 = weightRealPredict.max(fbaShipment.getSinglePassCrane());
                        fbaShipment.setWeightCalPredict(weightCalPredict22);

                        //梯度计重单价=(预估计重满足区间的值)
                        BigDecimal finalWeightCalPredict22 = weightCalPredict22;
                        tdjzPrice = logisticsMmodeGrads.stream().filter(logisticsMmodeGrads1 -> finalWeightCalPredict22.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                                && finalWeightCalPredict22.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
                        //抛重计重单价=(预估计重-抛重的值)
                        predVal = (weightVolPredict.subtract(weightRealPredict)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal finalPredVal = predVal;
                        pzjzPrice = logisticsMmodeInfoItems.stream().filter(logisticsMmodeGrads1 -> finalPredVal.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                                && finalPredVal.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
                        //计重单价=梯度计重单价
                        weightPrice = (tdjzPrice.size()!=0?tdjzPrice.get(0).getKg():BigDecimal.ZERO);
                        //MAX（预估抛重，单箱起重）（先进行约分）
                        weightVolPredictNew = precision((weightVolPredict.max(fbaShipment.getWeightCalBySingle())));
                        //抛重梯度计重单价=梯度计重单价
//                    BigDecimal finalWeightVolPredictNew = weightVolPredictNew;
//                    phjzPrice = logisticsMmodeGrads.stream().filter(logisticsMmodeGrads1 -> finalWeightVolPredictNew.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
//                            && finalWeightVolPredictNew.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
                        phweightPrice = (tdjzPrice.size()!=0?tdjzPrice.get(0).getKg():BigDecimal.ZERO);
                        //抛货计重费=预估抛重*梯度计重单价
                        fbaShipment.setJettisonWeightCharge(weightVolPredictNew.multiply(phweightPrice).setScale(2, BigDecimal.ROUND_HALF_UP));

                        //预估计重费=(预估计重*计重单价)
                        priceTranCalWeightPredict = (weightCalPredict22.multiply(weightPrice)).setScale(2, BigDecimal.ROUND_HALF_UP);

                        //超出品名=实际品名-免费品名数
                        num = (gradeNum.size()-logisticsMmode.getNumFreeProName());
                        //品名免费数
                        fbaShipment.setNumFreeProName(logisticsMmode.getNumFreeProName());
                        //占比
                        fbaShipment.setTradeNamePro(priceClearanceOpePrice);
                        //预估清光费
                        fbaShipment.setPriceClearanceOpePrice(fbaShipment.getPriceClearanceOpe());
                        fbaShipment.setNumProName(gradeNum.size());
                    }

                    //计重单价
                    fbaShipment.setJzPrice(weightPrice);
                    //抛货系数
                    fbaShipment.setJettisonCoe(predVal);
                    //梯度计重单价
                    fbaShipment.setTdjzPrice(tdjzPrice.size()!=0?tdjzPrice.get(0).getKg():BigDecimal.ZERO);
                    //抛重计重单价
                    fbaShipment.setPzjzPrice(pzjzPrice.size()!=0?pzjzPrice.get(0).getKg():BigDecimal.ZERO);

                    //设置表头附加费材质
                    fbaShipment.setPriceQualityExtra(texture);
                    //最大附加费材质
                    fbaShipment.setSurchargeMaterialMax(surchargeMaterialMax);
                    //设置预估材质附加费=材质计费*预估计重
                    fbaShipment.setPriceQualityExtraPredict(fbaShipment.getPriceQualityExtra().multiply(fbaShipment.getWeightCalPredict()).setScale(2, BigDecimal.ROUND_HALF_UP));

                    //品名
                    fbaShipment.setNumProNameBeyond(num>0?num:0);
                    //预估品名附加费 = 超出的品名*品名标准
                    fbaShipment.setPriceProNameExtraPredict(logisticsMmode.getPriceProNamePerOne().multiply(new BigDecimal(fbaShipment.getNumProNameBeyond())).setScale(2, BigDecimal.ROUND_HALF_UP));
                    //预估物流费用 = 预估计重运费+预估材质附加费+预估品名附加费+清关费
                    fbaShipment.setPriceTranPredict(fbaShipment.getPriceTranCalWeightPredict().
                            add(fbaShipment.getPriceQualityExtraPredict()).add(fbaShipment.getPriceProNameExtraPredict()
                            .add(fbaShipment.getPriceClearanceOpe())));

                    //设置第二步api商品信息
                    inboundShipmentItem = new InboundShipmentItem();
                    inboundShipmentItem.setSellerSKU(inboundShipmentPlanItem.getSellerSKU());
                    inboundShipmentItem.setFulfillmentNetworkSKU(inboundShipmentPlanItem.getFulfillmentNetworkSKU());
                    inboundShipmentItem.setQuantityShipped(inboundShipmentPlanItem.getQuantity());
                    inboundShipmentItem.setPrepDetailsList(prepDetails);
                    inboundShipmentItems.add(inboundShipmentItem);
                }

                //新增货件信息
                fbaShipmentMapper.insertFbaShipment(fbaShipment);
                //新增货件详情信息
                fbaShipmentDetailMapper.insertFbaShipmentDetailBatch(fbaShipmentDetailList);


                inboundShipmentRequest.setInboundShipmentHeader(inboundShipmentHeader);
                inboundShipmentRequest.setInboundShipmentItems(inboundShipmentItems);
                inboundShipmentRequest.setMarketplaceId(amazonShop.getMarketplaceIds());
                InboundShipmentResponse inboundShipmentResponse = api.createInboundShipment(inboundShipmentRequest, inboundShipmentPlan.getShipmentId());
                apiLogService.addApiLog("api", "AddParcel", "inboundShipmentResponse：" + inboundShipmentResponse.toString() + "," + "response:" + inboundShipmentResponse.getPayload(), "", 0, "创建货件createInboundShipment成功!");
            }
//        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            fbaPlanOrder1.setState("1");
            fbaPlanOrder1.setAuditTime(new Date());
            fbaPlanOrder1.setAuditUser(userInfo.getUserId());
            fbaPlanOrderMapper.update(fbaPlanOrder1);
        }catch (Exception e){
            apiResponse.setCode(200);
            apiResponse.setMsg("审核失败!");
        }

        apiResponse.setCode(0);
        apiResponse.setMsg("审核成功!");
        return apiResponse;
    }

    private BigDecimal precision(BigDecimal f){
        //根据数字未满5满5,未满10满10
        String s = f.stripTrailingZeros().toPlainString();
        String ff = f.toString();
        int rs = s.indexOf(".");
        if (rs != -1) {
            //取出第一位
            String first = s.substring(0,rs);
            //根据第一位小数5来判断，大于0.5以上进1,小于0.5的为0.5
            first = first + ".5";
            Double fD = Double.parseDouble(String.valueOf(f));
            Double firstD = Double.parseDouble(first);
            if (fD < firstD){
                ff = first;
            } else if(fD > firstD) {
                ff = String.valueOf(Math.round(fD));
            }
        }
        return new BigDecimal(ff);
    }

    /**
     * 手动生成装箱数据
     */
    private void generate(List<FbaBoxDetail> queryList,FbaBox fbaBox1,UserInfo userInfo,ApiResponse apiResponse,List<GaugeMaintenance> gaugeMaintenanceList
            ,List<FbaPlanOrderDetail> fbaPlanOrderDetailList){
        //每个商品的箱子数据
        List<FbaBoxDetail> fbaBoxDetailListNew = new ArrayList<>();
        FbaBoxDetail fbaBoxDetailNew;
        List<FbaBoxDetail> fbaBoxDetailList;

        Map<String, Object> params11 = new HashMap<String, Object>();
        params11.put("guid",fbaBox1.getLogisticsMmodeGuid());
        //查询物流方式
        LogisticsMmode logisticsMmode = logsticsMmodeMapper.queryFirstByGuid(params11);
        //获取物流方式详情
        Map<String, Object> params4 = new HashMap<String, Object>();
        params4.put("logisticsMmodeGuid",fbaBox1.getLogisticsMmodeGuid());
        List<LogisticsMmodeDetails> textureList = logsticsMmodeDetailsMapper.findLogisticsMmodeDetails(params4);
        //获取物流方式梯度
        List<LogisticsMmodeGrads> logisticsMmodeGradList = logsticsMmodeGradsMapper.findLogisticsMmodeGrads(params4);
        List<LogisticsMmodeGrads> logisticsMmodeGrads  = logisticsMmodeGradList.stream().filter(logisticsMmodeGrads1 ->
                "WLFS".equals(logisticsMmodeGrads1.getType())).collect(Collectors.toList());
        List<LogisticsMmodeGrads> logisticsMmodeInfoItems  = logisticsMmodeGradList.stream().filter(logisticsMmodeGrads1 ->
                "WLFSTDJZ".equals(logisticsMmodeGrads1.getType())).collect(Collectors.toList());
        List<LogisticsMmodeCk> logisticsMmodeCkList = logsticsMmodeCkMapper.findLogisticsMmodeCk(params4);

        params4.remove("logisticsMmodeGuid");
        params4.put("type","WLPMTD");
        //获取品名梯度详情
        List<LogisticsMmodeGrads> wlpmtdList = logsticsMmodeGradsMapper.findLogisticsMmodeGrads(params4);

        //单箱采购总价
        BigDecimal priceSingleBoxReqTol;

        FbaBoxDetail fbaBoxDetail;

        for (FbaPlanOrderDetail fbaPlanOrderDetail : fbaPlanOrderDetailList) {
            //根据头程箱数新增
            for (int j = 0; j < fbaPlanOrderDetail.getNumPlanDeliver() / fbaPlanOrderDetail.getGaugeMaintenanceNum(); j++) {
                fbaBoxDetailNew = new FbaBoxDetail();
                fbaBoxDetailNew.setGuid(RandomValueUtils.getGUID());
                //关联头程计划详情
                fbaBoxDetailNew.setCodeBox(fbaBox1.getCode());
                fbaBoxDetailNew.setCodeShipment(fbaBox1.getCodeShipment());
                fbaBoxDetailNew.setBoxIndex(j);
                fbaBoxDetailNew.setBUser(userInfo.getUserId());
                fbaBoxDetailNew.setBDept(userInfo.getDeptName());
                fbaBoxDetailNew.setDeleted(0);
                fbaBoxDetailNew.setCreateTime(new Date());
                fbaBoxDetailNew.setCreateUser(userInfo.getUserId());

                priceSingleBoxReqTol = BigDecimal.ZERO;
                fbaBoxDetailList = new ArrayList<>();
                //匹配箱规维护
                List<GaugeMaintenance> gaugeMaintenanceListNew = gaugeMaintenanceList.stream().filter(
                        gaugeMaintenance -> gaugeMaintenance.getId().equals(fbaPlanOrderDetail.getGaugeMaintenanceId())
                ).collect(Collectors.toList());
                if (gaugeMaintenanceListNew.size() == 0){
                    apiResponse.setMsg(fbaPlanOrderDetail.getCommodityCode() + "该箱规未维护,审核失败!");
                    apiResponse.setCode(400);
                    return;
                }
                //将每箱子的数据赋值到NumRealityDeliver字段上
                for (int i = 0; i < queryList.size(); i++) {
                    fbaBoxDetail = new FbaBoxDetail();
                    BeanUtils.copyProperties(queryList.get(i),fbaBoxDetail);
                    fbaBoxDetail.setNumPlanDeliver(String.valueOf(queryList.get(i).getNumPlanDeliver()));
                    if (queryList.get(i).getGuidKc().equals(fbaPlanOrderDetail.getGuidKc())){
                        fbaBoxDetail.setNumRealityDeliver(String.valueOf(fbaPlanOrderDetail.getGaugeMaintenanceNum()));
                        //计算单箱采购单价
                        priceSingleBoxReqTol = priceSingleBoxReqTol.add(new BigDecimal(fbaPlanOrderDetail.getGaugeMaintenanceNum()).multiply(new BigDecimal(queryList.get(i).getPriceIn())));
                    }
                    fbaBoxDetail.setSerial(String.valueOf(i));
                    fbaBoxDetailList.add(fbaBoxDetail);
                }

                fbaBoxDetailNew.setWeight(String.valueOf(gaugeMaintenanceListNew.get(0).getWeight()));
                fbaBoxDetailNew.setLength(String.valueOf(gaugeMaintenanceListNew.get(0).getLength()));
                fbaBoxDetailNew.setWidth(String.valueOf(gaugeMaintenanceListNew.get(0).getWidth()));
                fbaBoxDetailNew.setHeight(String.valueOf(gaugeMaintenanceListNew.get(0).getHeight()));
                //计算抛重
                BigDecimal weighVol =
                        (new BigDecimal(fbaBoxDetailNew.getLength()).multiply(new BigDecimal(fbaBoxDetailNew.getWidth()))
                                .multiply(new BigDecimal(fbaBoxDetailNew.getHeight())))
                                .divide(new BigDecimal(logisticsMmode.getCoefficientWeight()),2, RoundingMode.HALF_UP);
                fbaBoxDetailNew.setWeightVol(String.valueOf(weighVol));
                fbaBoxDetailNew.setPriceSingleBoxReq(priceSingleBoxReqTol);
                //将其他箱数的值统一赋值一个值上
                fbaBoxDetailNew.setProductInfo(JSONArray.toJSONString(fbaBoxDetailList));
                fbaBoxDetailListNew.add(fbaBoxDetailNew);
            }
        }

        List<FbaBoxDetail> fbaBoxDetailListInset = new ArrayList<>();
        //历史的商品信息
        List<FbaBoxDetail> fbaBoxDetailListOld;
        BigDecimal weightReal;
        BigDecimal weightVol;
        BigDecimal predVal;
        BigDecimal weightCal;
        BigDecimal weightCalNew;
        BigDecimal max_result;
        BigDecimal texture;
        BigDecimal weightPrice;
        BigDecimal phweightPrice;
        BigDecimal priceClearanceOpePrice;
        BigDecimal tradeNamePro;
        Boolean numWeightCal;
        Integer numProName;
        Integer num;
        Double numFreeProName;
        BigDecimal priceTranCalWeightPredict;
        BigDecimal warehouseSurcharge;
        BigDecimal weightVolPredictNew;
        String surchargeMaterialMax;
        BigDecimal weightCalBySingle;
        List<LogisticsMmodeGrads> tdjzPrice;
        List<LogisticsMmodeGrads> pzjzPrice;
        List<LogisticsMmodeGrads> phjzPrice;
        List<LogisticsMmodeGrads> qgPrice;
        Set<String> gradeNum;
        //总箱重
        weightReal = BigDecimal.ZERO;
        //总抛重
        weightVol = BigDecimal.ZERO;
        //最大的材质值
        texture = BigDecimal.ZERO;
        //最大值材质名称
        surchargeMaterialMax = "";
        //实际计重之和
        weightCal = BigDecimal.ZERO;
        //最大值
        max_result = BigDecimal.ZERO;
        //实际计重约分
        weightCalNew = BigDecimal.ZERO;
        //抛货系数
        predVal = BigDecimal.ZERO;
        //计重单价
        weightPrice = BigDecimal.ZERO;
        //抛重梯度计重单价
        weightVolPredictNew = BigDecimal.ZERO;
        //抛重计重单价
        phweightPrice = BigDecimal.ZERO;
        //实际计重费
        priceTranCalWeightPredict = BigDecimal.ZERO;
        //仓库附加计重费用
        warehouseSurcharge = BigDecimal.ZERO;
        //品名数除上限数
        tradeNamePro = BigDecimal.ZERO;
        //清关费
        priceClearanceOpePrice = BigDecimal.ZERO;
        //品名判断数值
        numWeightCal = true;
        //实际品名数
        numProName = 0;
        //超出品名
        num = 0;
        //实际品名免费数
        numFreeProName = 0.0;
        //品名数量
        gradeNum = new HashSet<>();
        for (int boxIndex = 0; boxIndex < fbaBoxDetailListNew.size(); boxIndex++) {
            //实际的商品信息
            fbaBoxDetailListOld = JSON.parseArray(fbaBoxDetailListNew.get(boxIndex).getProductInfo(), FbaBoxDetail.class);

            //计算抛重和实重的数据和采购价
            weightReal = weightReal.add(new BigDecimal(fbaBoxDetailListNew.get(boxIndex).getWeight()));
            weightVol = weightVol.add(new BigDecimal(fbaBoxDetailListNew.get(boxIndex).getWeightVol()));
            //MAX（单箱抛重，单箱起重）
            weightVolPredictNew = weightVolPredictNew.add(logisticsMmode.getWeightCalBySingle().max(new BigDecimal(fbaBoxDetailListNew.get(boxIndex).getWeightVol())));

            //物流方式==是
            if (fbaBox1.getStateShareTicketName().equals("是")) {
                if (fbaBox1.getLogisticsType().equals("快递")) {
                    //实际计重=MAX（实重,抛重,单箱起重）
                    max_result = logisticsMmode.getWeightCalBySingle().max(new BigDecimal(fbaBoxDetailListNew.get(boxIndex).getWeight()));
                    max_result = max_result.max(new BigDecimal(fbaBoxDetailListNew.get(boxIndex).getWeightVol()));
                    //实际计重之和
                    weightCal = weightCal.add(precision(max_result));
                    //实际计重=MAX（A1，单票起重）
                    weightCal = logisticsMmode.getSinglePassCrane().max(weightCal);
                }else {
                    //实际计重=MAX（实重,单箱起重）
                    max_result = logisticsMmode.getWeightCalBySingle().max(new BigDecimal(fbaBoxDetailListNew.get(boxIndex).getWeight()));
                    //实际计重之和
                    weightCal = weightCal.add(max_result);
                }
            } else {
                if (fbaBox1.getLogisticsType().equals("快递")) {
                    //实际计重=MAX（实重,抛重,单箱起重）
                    max_result = logisticsMmode.getWeightCalBySingle().max(new BigDecimal(fbaBoxDetailListNew.get(boxIndex).getWeight()));
                    max_result = max_result.max(new BigDecimal(fbaBoxDetailListNew.get(boxIndex).getWeightVol()));
                    //实际计重之和
                    weightCal = weightCal.add(precision(max_result));
                    fbaBox1.setWeightCalA1(weightCal);
                    //实际计重=MAX（A1，单票起重）
                    weightCal = logisticsMmode.getSinglePassCrane().max(weightCal);
                }else {
                    //实际计重=MAX（实重,抛重,单箱起重）
                    max_result = logisticsMmode.getWeightCalBySingle().max(new BigDecimal(fbaBoxDetailListNew.get(boxIndex).getWeight()));
                    max_result = max_result.max(new BigDecimal(fbaBoxDetailListNew.get(boxIndex).getWeightVol()));
                    //实际计重之和
                    weightCal = weightCal.add(max_result);
                }
            }

            //重新计算是第几箱子
            fbaBoxDetailListNew.get(boxIndex).setBoxIndex(boxIndex);

            for (FbaBoxDetail  fbaBoxDetail1 : fbaBoxDetailListOld){
                //TODO 判断十个箱子里面的值是否有值 再来判断是否需要判断品名数
                //不一样的品名数=(商品中文、海关编码、材质中文只要一个不同)
                String join = fbaBoxDetail1.getNameGoodsCn() + '-' + fbaBoxDetail1.getCodeGoodsHs() + '-' +fbaBoxDetail1.getNameMaterialCn();
                gradeNum.add(join);

                //判断是否是混合材质
                //TODO 判断十个箱子里面的值是否有值 再来判断是否需要判断材质值
                if (fbaBoxDetail1.getNameMaterialCn().indexOf(",") == -1) {
                    //赋值材质附加费(取最大值)
                    for (int j = 0; j < textureList.size(); j++) {
                        if (textureList.get(j).getMaterialName().equals(fbaBoxDetail1.getNameMaterialCn())) {
                            if (textureList.get(j).getMaterialCost().compareTo(texture) > 0) {
                                texture = (textureList.get(j).getMaterialCost());
                                surchargeMaterialMax = (textureList.get(j).getMaterialName());
                            }
                        }
                    }
                } else {
                    String[] nameMaterialCnList = fbaBoxDetail1.getNameMaterialCn().split(",");
                    for (String nameMaterialCn : nameMaterialCnList){
                        for (int j = 0; j < textureList.size(); j++) {
                            if (textureList.get(j).getMaterialName().equals(nameMaterialCn)) {
                                if (textureList.get(j).getMaterialCost().compareTo(texture) > 0) {
                                    texture = (textureList.get(j).getMaterialCost());
                                    surchargeMaterialMax = (textureList.get(j).getMaterialName());
                                }
                            }
                        }
                    }
                }
            }
        }

        //约分
        weightVolPredictNew = precision(weightVolPredictNew);

        //是否拼票是
        if (fbaBox1.getStateShareTicketName().equals("是")) {
            //计重约分
            if (fbaBox1.getLogisticsType().equals("快递")) {
                weightCalNew = weightCal;
            }else {
                weightCalNew = precision(weightCal);
            }
            //梯度计重单价=(实际计重满足区间的值)
            BigDecimal finalWeightCalNew = weightCalNew;
            tdjzPrice = logisticsMmodeGrads.stream().filter(logisticsMmodeGrads1 -> finalWeightCalNew.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                    && finalWeightCalNew.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
            //抛货系数=(抛重的值-计重的值)
            predVal = (weightVol.subtract(weightCalNew)).setScale(2, BigDecimal.ROUND_HALF_UP);
            //抛货计重单价=(抛货系数满足区间的值)
            BigDecimal finalPredVal = predVal;
            pzjzPrice = logisticsMmodeInfoItems.stream().filter(logisticsMmodeGrads1 -> finalPredVal.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                    && finalPredVal.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
            //计重单价=梯度计重单价+抛重计重单价
            weightPrice = (tdjzPrice.size()!=0?tdjzPrice.get(0).getKg():BigDecimal.ZERO).add(pzjzPrice.size()!=0?pzjzPrice.get(0).getKg():BigDecimal.ZERO);

            phweightPrice = (tdjzPrice.size()!=0?tdjzPrice.get(0).getKg():BigDecimal.ZERO);

            //抛重>实重，实际计重费=MIN(实际计重*计重单价,抛货计重费)；抛重<实重，实际计重费=实际计重*计重单价；
            priceTranCalWeightPredict = (weightCalNew.multiply(weightPrice)).setScale(2, BigDecimal.ROUND_HALF_UP);
            if (weightVol.compareTo(weightReal) > 0){
                if (priceTranCalWeightPredict.compareTo(weightVolPredictNew.multiply(phweightPrice))>=0){
                    fbaBox1.setPriceTranCalWeightPredict(weightVolPredictNew.multiply(phweightPrice));
                }else {
                    fbaBox1.setPriceTranCalWeightPredict(priceTranCalWeightPredict);
                }
            }else {
                fbaBox1.setPriceTranCalWeightPredict(priceTranCalWeightPredict);
            }
            //1.实际计重<单票起重的二分之一,实际品名数=免费品名数/2&向下取整
            numWeightCal = weightCalNew.compareTo(fbaBox1.getSinglePassCrane().divide(new BigDecimal(2)))<0;
            //实际品名数
            numProName = gradeNum.size();
            if (numWeightCal){
                numFreeProName = Math.floor(fbaBox1.getNumFreeProNameNew()/2.0);
            }
            //2.实际计重>=单票起重的二分之一,实际品名数=免费品名数/2&向上取整
            if (!numWeightCal && weightCalNew.compareTo(fbaBox1.getSinglePassCrane())<0){
                numFreeProName = Math.ceil(fbaBox1.getNumFreeProNameNew()/2.0);
            }
            if (weightCalNew.compareTo(fbaBox1.getSinglePassCrane()) >= 0){
                //3.实际计重>=单票起重,实际品名数=免费品名数
                numFreeProName = fbaBox1.getNumFreeProNameNew().doubleValue();
            }
            //超出品名=实际品名-实际免费品名数
            num = numProName-numFreeProName.intValue();
            //品名免费数
            fbaBox1.setNumFreeProName(Integer.valueOf(numFreeProName.intValue()));
            fbaBox1.setNumProName(numProName);
            //清关费=清关费*清关占比
            if (fbaBox1.getNumMaxProName()!= 0){
                //品名数/上限数
                tradeNamePro = new BigDecimal(gradeNum.size()).divide(new BigDecimal(logisticsMmode.getNumMaxProName()),2,RoundingMode.HALF_UP);
                BigDecimal finalTradeNamePro = tradeNamePro;
                qgPrice = wlpmtdList.stream().filter(logisticsMmodeGrads1 -> finalTradeNamePro.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                        && finalTradeNamePro.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
                priceClearanceOpePrice = qgPrice.size()!=0?qgPrice.get(0).getKg():BigDecimal.ZERO;
            }
            //预估清光费(物流方式清光费*品名占比)
            fbaBox1.setPriceClearanceOpe((logisticsMmode.getPriceClearanceOpe().multiply(priceClearanceOpePrice)).divide(new BigDecimal(100),2,RoundingMode.HALF_UP));
            //清光费单价
            fbaBox1.setPriceClearanceOpePrice(logisticsMmode.getPriceClearanceOpe());
        } else {
            //计重约分
            if (fbaBox1.getLogisticsType().equals("快递")) {
                weightCalNew = weightCal;
            }else {
                weightCalNew = new BigDecimal(Math.ceil(weightCal.doubleValue()));
                fbaBox1.setWeightCalA1(weightCalNew);
                //实际计重=MAX（A1，单票起重）
                weightCalNew = logisticsMmode.getSinglePassCrane().max(weightCalNew);
            }
            //梯度计重单价=(实际计重满足区间的值)
            BigDecimal finalWeightCalNew = weightCalNew;
            tdjzPrice = logisticsMmodeGrads.stream().filter(logisticsMmodeGrads1 -> finalWeightCalNew.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                    && finalWeightCalNew.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
            //抛货系数=(抛重的值-计重的值)
            predVal = (weightVol.subtract(weightCalNew)).setScale(2, BigDecimal.ROUND_HALF_UP);
            //抛货计重单价=(抛货系数满足区间的值)
            BigDecimal finalPredVal = predVal;
            pzjzPrice = logisticsMmodeInfoItems.stream().filter(logisticsMmodeGrads1 -> finalPredVal.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                    && finalPredVal.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
            //计重单价=梯度计重单价+抛重计重单价
            weightPrice = (tdjzPrice.size()!=0?tdjzPrice.get(0).getKg():BigDecimal.ZERO);
            phweightPrice = (tdjzPrice.size()!=0?tdjzPrice.get(0).getKg():BigDecimal.ZERO);

            //实际计重费=(预估计重*计重单价)
            fbaBox1.setPriceTranCalWeightPredict((weightCalNew.multiply(weightPrice)).setScale(2, BigDecimal.ROUND_HALF_UP));
            //超出品名=实际品名-实际免费品名数
            num = gradeNum.size()-numFreeProName.intValue();
            //实际清光费
            fbaBox1.setPriceClearanceOpe(logisticsMmode.getPriceClearanceOpe());
            fbaBox1.setNumProName(gradeNum.size());
        }

        fbaBox1.setWarehouseSurchargePrice(BigDecimal.ZERO);

        //仓库附加计重费用 = 仓库附件计重单价*实际计重
        warehouseSurcharge = (weightCalNew.multiply(fbaBox1.getWarehouseSurchargePrice())).setScale(2, BigDecimal.ROUND_HALF_UP);
        fbaBox1.setWarehouseSurcharge(warehouseSurcharge);
        fbaBox1.setPriceTranCalWeightPredict(fbaBox1.getPriceTranCalWeightPredict().add(warehouseSurcharge));

        //实际实重
        fbaBox1.setWeightReal(weightReal);
        //实际抛重
        fbaBox1.setWeightVol(weightVol);
        //装箱计重
        fbaBox1.setWeightCal(weightCalNew);
        //头程箱数
        fbaBox1.setNumBox(fbaBoxDetailListNew.size());
        //抛货系数
        fbaBox1.setJettisonCoe(predVal);
        //梯度计重单价
        fbaBox1.setTdjzPrice(tdjzPrice.size()!=0?tdjzPrice.get(0).getKg():BigDecimal.ZERO);
        //抛货计重单价
        fbaBox1.setPzjzPrice(pzjzPrice.size()!=0?pzjzPrice.get(0).getKg():BigDecimal.ZERO);
        //计重单价
        fbaBox1.setJzPrice(weightPrice);
        //抛货计重费
        fbaBox1.setJettisonWeightCharge(weightVolPredictNew.multiply(phweightPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
        //设置表头附加费材质
        fbaBox1.setPriceQualityExtra(texture);
        //最大附加费材质
        fbaBox1.setSurchargeMaterialMax(surchargeMaterialMax);
        //设置实际材质附加费=材质计费*实际计重
        fbaBox1.setPriceQualityExtraPredict(texture.multiply(weightCalNew).setScale(2, BigDecimal.ROUND_HALF_UP));
        //品名
        fbaBox1.setNumProNameBeyond(num>0?num:0);
        //占比
        fbaBox1.setTradeNamePro(priceClearanceOpePrice);
        //实际品名附加费 = 超出的品名*品名标准
        fbaBox1.setPriceProNameExtraPredict(logisticsMmode.getPriceProNamePerOne().multiply(new BigDecimal(fbaBox1.getNumProNameBeyond())).setScale(2, BigDecimal.ROUND_HALF_UP));
        //实际物流费用 = 实际计重运费+实际材质附加费+实际品名附加费+实际清关费
        fbaBox1.setActualLogisticsFreight(fbaBox1.getPriceTranCalWeightPredict().
                add(fbaBox1.getPriceQualityExtraPredict()).add(fbaBox1.getPriceProNameExtraPredict()
                .add(fbaBox1.getPriceClearanceOpe())));

        //判断是否是抛重发货 -- 进行逻辑计算
        if (fbaBox1.getLoadDelivery().equals("是")){
            //实际抛发清关费=清关费单价
            fbaBox1.setPriceClearanceOpePf(logisticsMmode.getPriceClearanceOpe());
            //抛发实际品名免费数=品名免费数
            fbaBox1.setNumFreeProNamePf(logisticsMmode.getNumFreeProName());
            //抛发超品名数量【=实际品名数-抛发实际品名免费数】
            int numPf = fbaBox1.getNumProName() - fbaBox1.getNumFreeProNamePf();
            numPf = numPf>0?numPf:0;
            //实际抛发品名附加费、费用说明：实际抛发品名附加费=超品名数量*品名附加费单价
            fbaBox1.setPriceProNameExtraPredictPf(logisticsMmode.getPriceProNamePerOne().multiply(new BigDecimal(numPf)).setScale(2, BigDecimal.ROUND_HALF_UP));
            //抛发计重：【=MAX（装箱抛重，单票起重）约分】
            BigDecimal weightCalPf = precision(logisticsMmode.getSinglePassCrane().max(weightVol));
            //实际抛发材质附加费、费用说明：实际抛发材质附加费=MAX（装箱抛重，单票起重）*材质附加单价
            fbaBox1.setPriceQualityExtraPredictPf(weightCalPf.multiply(fbaBox1.getPriceQualityExtra()).setScale(2, BigDecimal.ROUND_HALF_UP));
            //抛发计重单价：【抛发计重对应的梯度价】
            List<LogisticsMmodeGrads> pfLogisticsMmodeGrads;
            BigDecimal pfjzPrice;
            pfLogisticsMmodeGrads = logisticsMmodeGrads.stream().filter(logisticsMmodeGrads1 -> weightCalPf.compareTo(logisticsMmodeGrads1.getStartSection()) >= 0
                    && weightCalPf.compareTo(logisticsMmodeGrads1.getEndSection()) <= 0).collect(Collectors.toList());
            pfjzPrice = (pfLogisticsMmodeGrads.size()!=0?pfLogisticsMmodeGrads.get(0).getKg():BigDecimal.ZERO);
            BigDecimal warehouseSurchargepf = (weightCalPf.multiply(fbaBox1.getWarehouseSurchargePrice())).setScale(2, BigDecimal.ROUND_HALF_UP);
            fbaBox1.setWarehouseSurchargePf(warehouseSurchargepf);
            //实际抛发计重运费、费用说明：实际抛发计重运费=MAX（装箱抛重，单票起重）*抛发计重单价+仓库附加计重费用
            fbaBox1.setPriceTranCalWeightPredictPf(((weightCalPf.multiply(pfjzPrice)).add(warehouseSurchargepf)).setScale(2, BigDecimal.ROUND_HALF_UP));
            //实际抛发物流运费、费用说明：实际抛发物流运费=实际抛发计重运费+实际抛发材质附加费+实际抛发品名附加费+实际抛发清关费
            fbaBox1.setActualLogisticsFreightPf(fbaBox1.getPriceTranCalWeightPredictPf()
                    .add(fbaBox1.getPriceQualityExtraPredictPf())
                    .add(fbaBox1.getPriceProNameExtraPredictPf())
                    .add(fbaBox1.getPriceClearanceOpePf()));
        }
        fbaBox1.setUpdateTime(new Date());
        fbaBox1.setUpdateUser(userInfo.getUserId());
        fbaBox1.setStatePrint("3");
        fbaBox1.setStatePrintName("配货清单和商品标和透明标已打印");
        fbaBox1.setState("2");
        fbaBox1.setStateName("已装箱");

        //新增详情数据
        fbaBoxDetailMapper.batchInsert(fbaBoxDetailListNew);

        //        //修改装箱详情
        fbaBoxMapper.updateByGuid(fbaBox1);
    }

    private void addCancel(FbaBox fbaBox,Map<String, Object> params,FbaCancel fbaCancel,UserInfo userInfo,ApiResponse apiResponse){
        try {
            ModuleNidAndBid moduleNidAndBid;
            Map<String, Object> params2;
            //查询头程货件最新数据
            params2 = new HashMap<String, Object>();
            params2.put("moduleTable", "TP_FbaCancel");
            moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params2);
            //新增拆箱单数据
            fbaCancel.setCodeBox(fbaBox.getCode());
            fbaCancel.setCodePlanOrder(fbaBox.getCodePlan());
            fbaCancel.setCodeCancel(moduleNidAndBid.getBid());
            fbaCancel.setCodeCompany(fbaBox.getCodeCompany());
            fbaCancel.setNameCompany(fbaBox.getNameCompany());
            fbaCancel.setRemark(params.get("remark").toString());
            fbaCancel.setState("1");
            fbaCancel.setCreateUser(userInfo.getUserId());
            fbaCancel.setCreateTime(new Date());
            fbaCancel.setGuid(RandomValueUtils.getGUID());
            fbaCancel.setIid(0);
            fbaCancel.setNid(moduleNidAndBid.getNid());
            fbaCancel.setBid(moduleNidAndBid.getBid());
            fbaCancel.setCid(userInfo.getCid());
            fbaCancel.setCidName(userInfo.getCidName());
            fbaCancel.setbUser(userInfo.getUserId());
            fbaCancel.setbUserName(userInfo.getUserName());
            fbaCancel.setbDept(userInfo.getDeptPath());
            fbaCancel.setbDeptName(userInfo.getDeptName());
            fbaCancel.setbPosition(userInfo.getPositionNameDa());
            fbaCancel.setaUser(userInfo.getUserId());
            fbaCancel.setaUserName(userInfo.getUserName());
            fbaCancel.setaDept(userInfo.getDeptPath());
            fbaCancel.setaDeptName(userInfo.getDeptName());
            fbaCancel.setaPosition(userInfo.getPositionNameDa());
            fbaCancel.setCreateTime(new Date());
            fbaCancel.setShipmentId(fbaBox.getShipmentId());
            fbaCancel.setCodeShipment(fbaBox.getCodeShipment());
            fbaCancel.setvGsJc(fbaBox.getvGsJc());
            fbaCancel.setWeightReal(fbaBox.getWeightReal());
            fbaCancel.setUpdateUser(fbaBox.getUpdateUser());
            fbaCancel.setPackingPerson(fbaBox.getPackingPerson());
            fbaCancelMapper.insertFbaCancel(fbaCancel);
        }catch (Exception e){
            apiResponse.setMsg("新增取消单失败!");
            apiResponse.setCode(400);
        }
    }

    /**
     * 新增海外仓尾程数据
     */
    private void addHwTailprogram(ApiResponse apiResponse,FbaBox fbaBox1,List<FbaBoxDetail> fbaBoxDetailList,Map<Integer,Integer> numBiDc){
        HwTailprogramApi hwTailprogramApi = null;
        ModuleNidAndBid moduleNidAndBid;
        Map<String, Object> params2;
        List<FbaBoxDetail> fbaBoxDetailListNew = null;
        try {
            Integer numcommodity = 0;
            Integer lucencyNum = 0;
            if (fbaBoxDetailList.size() != 0){
                fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(0).getProductInfo(), FbaBoxDetail.class);
            }
            for (int i = 0; i < fbaBoxDetailListNew.size(); i++) {
                numcommodity = numcommodity + numBiDc.get(i);
                //有透明标的商品数量
                if (fbaBoxDetailListNew.get(i).getIsSign().equals("是")){
                    lucencyNum = lucencyNum + numBiDc.get(i);
                }
            }
            //查询头程货件最新数据
            params2 = new HashMap<String, Object>();
            params2.put("moduleTable", "HW_TailProgram");
            moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params2);    //有事务控制，制单异常不跳过单号
            hwTailprogramApi = new HwTailprogramApi();
            hwTailprogramApi.setGuid(RandomValueUtils.getGUID());
            hwTailprogramApi.setBid(moduleNidAndBid.getBid());
            hwTailprogramApi.setCodebox(fbaBox1.getCode());
            hwTailprogramApi.setCodeshipment(fbaBox1.getCodeShipment());
            hwTailprogramApi.setCodeplan(fbaBox1.getCodePlan());
            hwTailprogramApi.setCodecompany(fbaBox1.getCodeCompany());
            hwTailprogramApi.setVgsjc(fbaBox1.getvGsJc());
            hwTailprogramApi.setSellerid(fbaBox1.getSellerId());
            hwTailprogramApi.setShipmentid(fbaBox1.getShipmentId());
            hwTailprogramApi.setNumbox(fbaBox1.getNumBox());
            hwTailprogramApi.setDestinationfulfillmentcenterid(fbaBox1.getDestinationFulfillmentCenterId());
            hwTailprogramApi.setAddressline1(fbaBox1.getAddressLine1());
            hwTailprogramApi.setAddressline2(fbaBox1.getAddressLine2());
            hwTailprogramApi.setCity(fbaBox1.getCity());
            hwTailprogramApi.setCountrycode(fbaBox1.getCountryCode());
            hwTailprogramApi.setWeightreal(new Double(String.valueOf(fbaBox1.getWeightReal())));
            hwTailprogramApi.setWeightvol(new Double(String.valueOf(fbaBox1.getWeightVol())));
            hwTailprogramApi.setWeightcal(0.0);
            hwTailprogramApi.setNumcommodity(numcommodity);
            hwTailprogramApi.setLaunchwarehouse(fbaBox1.getWarehouseAddress());
            hwTailprogramApi.setLastvoyagecharge(0.0);
            hwTailprogramApi.setAddition(0.0);
            hwTailprogramApi.setStateName("制单环节");
            hwTailprogramApi.setCreatetime(new Date());
            hwTailprogramApi.setStockOutCode(null);
            hwTailprogramApi.setStatePrintName("无");
            hwTailprogramApi.setLucencyCommission(0.0);
            hwTailprogramApi.setLucencyNum(lucencyNum);
            hwTailprogramApi.setHjTrackingCode(fbaBox1.getTrackingCode());
            hwTailprogramMapper.insert(hwTailprogramApi);
        }catch (Exception e){
            apiResponse.setMsg("新增尾程单失败!");
            apiResponse.setCode(400);
            return;
        }


        try {
            //新增明细
            HwTailprogramdetail hwTailprogramdetail;
            for (FbaBoxDetail fbaBoxDetail : fbaBoxDetailList){
                hwTailprogramdetail = new HwTailprogramdetail();
                hwTailprogramdetail.setGuid(RandomValueUtils.getGUID());
                hwTailprogramdetail.setTpcode(hwTailprogramApi.getBid());
                hwTailprogramdetail.setBoxindex(fbaBoxDetail.getBoxIndex());
                hwTailprogramdetail.setProductinfo(fbaBoxDetail.getProductInfo());
                hwTailprogramdetail.setLength(fbaBoxDetail.getLength());
                hwTailprogramdetail.setWidth(fbaBoxDetail.getWidth());
                hwTailprogramdetail.setHeight(fbaBoxDetail.getHeight());
                hwTailprogramdetail.setWeight(fbaBoxDetail.getWeight());
                hwTailprogramdetail.setWeightvol(fbaBoxDetail.getWeightVol());
                hwTailprogramdetail.setBoxnum(fbaBoxDetail.getBoxNum());
                hwTailprogramdetail.setPurchaseprice(fbaBoxDetail.getPurchasePrice());
                hwTailprogramdetail.setTrackingcode(fbaBoxDetail.getTrackingCode());
                hwTailprogramdetail.setPricesingleboxreq(new Double(String.valueOf(fbaBox1.getPriceSingleBoxReq())));
                hwTailprogramdetailMapper.insert(hwTailprogramdetail);
            }
        }catch (Exception e){
            apiResponse.setMsg("新增尾程明细单失败!");
            apiResponse.setCode(400);
            return;
        }
    }

    /**
     * 删除海外仓尾程数据
     */
    private void delHwTailprogram(ApiResponse apiResponse,FbaBox fbaBox1){
        Map<String, Object> params2;
        params2 = new HashMap<String, Object>();
        params2.put("codeBox", fbaBox1.getCode());
        HwTailprogramApi hwTailprogramApi = hwTailprogramMapper.queryFirstRecord1(params2);
        if (hwTailprogramApi != null){
            apiResponse.setMsg("已生成尾程单,不允许回退,如需回退,请删除尾程单!");
            apiResponse.setCode(400);
            return;
        }
    }

    private ApiResponse addFbaWarehousing(FbaBox fbaBox,UserInfo userInfo,ApiResponse apiResponse,List<HwTailprogramdetail> hwTailprogramdetaiList
                     ,AmazonShop amazonShop){
        FbaWarehousing fbaWarehousing = new FbaWarehousing();
        try {
            ModuleNidAndBid moduleNidAndBid;
            Map<String, Object> params2;
            //查询头程货件最新数据
            params2 = new HashMap<String, Object>();
            params2.put("moduleTable", "TP_FbaWarehousing");
            moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params2);
            //新增fba入仓单数据
            fbaWarehousing.setShipmentId(fbaBox.getShipmentId());
            fbaWarehousing.setTrackingCode(fbaBox.getTrackingCode());
            fbaWarehousing.setDestinationFulfillmentCenterId(fbaBox.getDestinationFulfillmentCenterId());
            fbaWarehousing.setCodePlan(fbaBox.getCodePlan());
            fbaWarehousing.setCodeBox(fbaBox.getCode());
            fbaWarehousing.setCodeCompany(fbaBox.getCodeCompany());
            fbaWarehousing.setvGsJc(fbaBox.getvGsJc());
            fbaWarehousing.setSellerId(fbaBox.getSellerId());
            fbaWarehousing.setNameLogsticsWay(fbaBox.getNameLogsticsWay());
            fbaWarehousing.setNumBox(fbaBox.getNumBox());
            fbaWarehousing.setPackingTime(fbaBox.getUpdateTime());
            fbaWarehousing.setAuditTime(fbaBox.getAuditTime());
            fbaWarehousing.setStateName("处理中");
            fbaWarehousing.setNid(moduleNidAndBid.getNid());
            fbaWarehousing.setBid(moduleNidAndBid.getBid());
            fbaWarehousing.setCid(userInfo.getCid());
            fbaWarehousing.setbUser(userInfo.getUserId());
            fbaWarehousing.setbDept(userInfo.getDeptPath());
            fbaWarehousing.setbPosition(userInfo.getPositionNameDa());
            fbaWarehousing.setCreateTime(new Date());
            fbaWarehousing.setDeleted(false);
            fbaWarehousing.setCodeShipment(fbaBox.getCodeShipment());
            fbaWarehousing.setShopName(amazonShop.getShopName());
            fbaWarehousing.setCreationMethod(fbaBox.getCreationMethod());
            fbaWarehousingMapper.insert(fbaWarehousing);
        }catch (Exception e){
            apiResponse.setMsg("新增FBA入仓单失败!");
            apiResponse.setCode(400);
            return apiResponse;
        }

        FbaWarehousingDetail fbaWarehousingDetail;
        for (HwTailprogramdetail hwTailprogramdetail : hwTailprogramdetaiList){
            try {
                //新增入仓单明细
                fbaWarehousingDetail = new FbaWarehousingDetail();
                fbaWarehousingDetail.setGuid(RandomValueUtils.getGUID());
                fbaWarehousingDetail.setCode(fbaWarehousing.getBid());
                fbaWarehousingDetail.setBoxIndex(hwTailprogramdetail.getBoxindex());
                fbaWarehousingDetail.setProductInfo(hwTailprogramdetail.getProductinfo());
                fbaWarehousingDetail.setTrackingCode(hwTailprogramdetail.getTrackingcode());
                fbaWarehousingDetailMapper.insert(fbaWarehousingDetail);
            }catch (Exception e){
                apiResponse.setMsg("新增入仓单明细失败!");
                apiResponse.setCode(400);
                return apiResponse;
            }
        }
        return apiResponse;
    }

    @Override
    public void getCs() {
        ApiResponse apiResponse = new ApiResponse();
        List<FbaBox> list;
        Address address;
        SellerSecretsVO secretsVO;
        FbaInboundApi api;
        Map<String, Object> params1 = null;
        UserInfo userInfo;
        List<FbaBoxDetail> fbaBoxDetails;
        File file;
        FileInputStream input;
        HSSFWorkbook workbook;
        HSSFSheet sheet;
        HSSFRow row;
        HSSFCell cell = null;
        FbaBoxDetail fbaBoxDetailNew;
        FileOutputStream out;
        FeedsApi feedsApi;
        AmazonShop amazonShop = null;
//        List<AmazonShopProduct> queryProduct = amazonShopProductMapper.findAmazonShopProductList(params1);
//        for (AmazonShopProduct amazonShopProduct : queryProduct){
//            if (amazonShopProduct.getAsin() == null){
//                continue;
//            }
//            amazonShop = amazonShopMapper.findAmazonShopByGuid(amazonShopProduct.getShopGuid());
            amazonShop = amazonShopMapper.findAmazonShopByGuid("da6ec4e4-043a-4505-ab8f-401c7794521a");
//            List<String> sellerSKUList = new ArrayList<>();
//
//            sellerSKUList.add(amazonShopProduct.getSellerSku());

            //查询网店信息
            address = new Address();
            secretsVO = new SellerSecretsVO();
            getAmazonShop(amazonShop, address, secretsVO);
            api = Helper.buildApi(secretsVO, FbaInboundApi.class);
            List<String> shipmentIdList = new ArrayList<>();
            shipmentIdList.add("FBA15HT82J7F");
            String code = "";
            //根据站点对应的货件站点
            AmazonSellerUrlEnum[] AmazonSellerUrlEnumList = AmazonSellerUrlEnum.values();
            for (AmazonSellerUrlEnum amazonSellerUrlEnum : AmazonSellerUrlEnumList){
                if(amazonShop.getCountryName().equals(amazonSellerUrlEnum.getCnName())){
                    code = amazonSellerUrlEnum.getCode();
                }
            }

            try {

//                GetPrepInstructionsResponse getPrepInstructionsResponseList = api.getPrepInstructions(code, sellerSKUList, null);
            GetShipmentItemsResponse getShipmentItemsResponse = api.getShipmentItemsByShipmentId("FBA17TD3LWM9", amazonShop.getMarketplaceIds());
            getShipmentItemsResponse = getShipmentItemsResponse;

//                StringBuilder prepInstructionList = new StringBuilder();
//                if (getPrepInstructionsResponseList != null){
//                    GetPrepInstructionsResult payload = getPrepInstructionsResponseList.getPayload();
//                    if (payload.getSkUPrepInstructionsList() != null){
//                        for(SKUPrepInstructions skuPrepInstructions :payload.getSkUPrepInstructionsList()){
//                            if (skuPrepInstructions.getPrepInstructionList() != null){
//                                for (PrepInstruction prepInstruction : skuPrepInstructions.getPrepInstructionList()){
//                                    if(prepInstructionList.length()!=0){
//                                        prepInstructionList.append(","+prepInstruction.getValue());
//                                    }else{
//                                        prepInstructionList.append(prepInstruction.getValue());
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//                amazonShopProduct.setPrepInstructionList(prepInstructionList.toString());
//                amazonShopProductMapper.update(amazonShopProduct);
            } catch (ApiException e) {
                e.printStackTrace();
            }

//        }

    }


    /**
     * 完成单拆箱
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public ApiResponse devanningWc(Map<String, Object> params) throws Exception {
        ApiResponse apiResponse = new ApiResponse();

        Map<String, Object> paramHw = new HashMap<String, Object>();
        String code = params.get("code").toString();
        if(params.get("devanning") == null || params.get("remark") == null || params.get("code") == null){
            apiResponse.setMsg("拆箱信息不允许为空!");
            apiResponse.setCode(400);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return apiResponse;
        }

        HwTailprogramApi hwTailprogramApi1;
        List<AccountDetailedForCompany> accountList = null;
        SysAccountBandDept sysAccountBandDept;
        AccountCountForCompany logisticsAccount;
        AccountCountForCompany operationAccount;
        AccountCountForCompany warehousingAccount;
        UserInfo userInfo;
        Double transparencyProject;
        Double boxProject = 0.0;
        Double priceTranPredict1 = 0.0;
        Map<String, Object> params1;
        List<FbaBoxDetail> fbaBoxDetailList;
        List<FbaBoxDetail> fbaBoxDetailListNew = null;
        StringBuffer stringBuffer = null;
        FbaDevanningDetail fbaDevanningDetail;
        Map<String, Object> params2;
        List<FbaBox> fbaBoxList;
        FbaShipment fbaShipment;
        FbaPlanOrder fbaPlanOrder;
        ModuleNidAndBid moduleNidAndBid;
        FbaBoxDetail fbaBoxDetaiNew;
        FbaDevanning fbaDevanning;
        try {
            FbaBox fbaBox1 = fbaBoxMapper.queryFirstByCode(code);
            if (fbaBox1 == null) {
                apiResponse.setMsg(code + "头程装箱单不存在!");
                apiResponse.setCode(400);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            //海外仓逻辑
            if (fbaBox1.getIsDeliver() == 1){
                paramHw.put("moduleTable", "HW_TailProgram");
                paramHw.put("entity", new HwTailprogramApi());
                paramHw.put("codeBox", fbaBox1.getCode());
                hwTailprogramApi1 = hwTailprogramMapper.queryFirstRecord1(paramHw);
                if (hwTailprogramApi1 != null){
                    apiResponse.setCode(400);
                    apiResponse.setMsg("该单据存在海外尾程单,不允许拆箱!");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
            }else {
                if (!fbaBox1.getStateTrackName().equals("无")) {
                    apiResponse.setMsg(code + "该物流状态不允许拆箱,请核实后在操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }
            }
            if (fbaBox1.getDeleted() == true) {
                apiResponse.setMsg(code + "状态已删除,不允许拆箱,请核实后在操作!");
                apiResponse.setCode(400);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            FbaShipment fbaShipment1 = fbaShipmentMapper.queryFirstByCode(fbaBox1.getCodeShipment());
            if (fbaShipment1 == null){
                apiResponse.setMsg("头程货件不存在!");
                apiResponse.setCode(400);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            if ("自动".equals(fbaBox1.getCreationMethod())) {
                apiResponse.setMsg("创建方式只允许是手动下,请核实后在操作!");
                apiResponse.setCode(400);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }

            accountList =new ArrayList<>();
            userInfo = userInfoMapper.findByUserId(fbaBox1.getaUser());
            if (userInfo == null) {
                apiResponse.setMsg(fbaBox1.getCode() + "头程单名下的用户不存在!");
                apiResponse.setCode(400);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            operationAccount = accountCountForCompanyMapper.queryFirstByVGsBm(fbaBox1.getCodeCompany());
            if (operationAccount == null){
                apiResponse.setMsg("运营公司实时资金不存在,请核实后再操作!");
                apiResponse.setCode(400);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }

            //查询仓储部绑定账户
            sysAccountBandDept = sysAccountBandDeptMapper.findByAccountId("CCB");
            if (sysAccountBandDept == null){
                apiResponse.setMsg("仓储部绑定账户未启用或不存在,请核实后再操作!");
                apiResponse.setCode(400);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            // 仓储部绑定账户增加物流费用
            warehousingAccount = accountCountForCompanyMapper.queryFirstByVGsBm(sysAccountBandDept.getvGsBm());
            if (warehousingAccount == null){
                apiResponse.setMsg("仓储部实时资金不存在,请核实后再操作!");
                apiResponse.setCode(400);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }

            //头程冻结的实际物流费用
            priceTranPredict1 = Double.valueOf(fbaBox1.getActualLogisticsFreight().toString());

            //查询头程货件详情信息
            params1 = new HashMap<String, Object>();
            //头程计划单下所有箱子数据
            params1.put("codeBox1", fbaBox1.getCode());
            fbaBoxDetailList = fbaBoxDetailMapper.findFbaBoxDetail(params1);

            if (fbaBoxDetailList.size() == 0) {
                apiResponse.setMsg("头程单名下的商品信息不存在!");
                apiResponse.setCode(400);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }
            //计算装箱物料费 + 透明计划贴标费
            boxProject = Double.valueOf(fbaBox1.getNumBox()) * 15;

            transparencyProject = 0.0;
            Map<Integer, Integer> numBiDc;
            numBiDc = new HashMap<>();
            if (fbaBoxDetailList.size() != 0) {
                for (int i = 0; i < fbaBoxDetailList.size(); i++) {
                    fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(i).getProductInfo(), FbaBoxDetail.class);
                    for (int j = 0; j < fbaBoxDetailListNew.size(); j++) {
                        if (numBiDc.get(j) == null) {
                            numBiDc.put(j, new Integer(fbaBoxDetailListNew.get(j).getNumRealityDeliver().equals("") ? "0" : fbaBoxDetailListNew.get(j).getNumRealityDeliver()));
                        } else {
                            numBiDc.put(j, numBiDc.get(j) + (new Integer(fbaBoxDetailListNew.get(j).getNumRealityDeliver().equals("") ? "0" : fbaBoxDetailListNew.get(j).getNumRealityDeliver())));
                        }
                    }
                }
                fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(0).getProductInfo(), FbaBoxDetail.class);
                stringBuffer = new StringBuffer();
                for (int j = 0; j < fbaBoxDetailListNew.size(); j++) {
                    //修改库存总数量
                    if (params.get("devanning").equals("0")) {
                        updateNum(fbaBox1,fbaBoxDetailListNew.get(j), apiResponse, userInfo, 3, numBiDc.get(j));
                    }else if (params.get("devanning").equals("1")) {
                        updateNum(fbaBox1,fbaBoxDetailListNew.get(j), apiResponse, userInfo, 4, numBiDc.get(j));
                    }

                    if (apiResponse.getCode() == 400) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return apiResponse;
                    }
                    if (!fbaBoxDetailListNew.get(j).getvDFilesDefault().equals("无附件")){
                        //详情备注赋值
                        stringBuffer.append(fbaBoxDetailListNew.get(j).getCommodityCode()+",数量"+numBiDc.get(j)+"个,");
                        //累加透明计划贴标费
                        transparencyProject = transparencyProject + (Double.valueOf(numBiDc.get(j)) * (0.6));
                    }
                    for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailList) {
                        fbaBoxDetai.setTrackingCode(null);
                        fbaBoxDetailMapper.updateByGuid(fbaBoxDetai);
                    }
                }
            }

            //0.正常拆箱|1.复建
            if (params.get("devanning").equals("0")) {
                fbaDevanning = new FbaDevanning();
                addDevanning(fbaBox1, params, fbaDevanning, userInfo, apiResponse, fbaShipment1,0);
                if (apiResponse.getCode() == 400) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                if (fbaBoxDetailList.size() != 0) {
                    fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(0).getProductInfo(), FbaBoxDetail.class);
                    for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailListNew) {
                        //新增拆箱详情
                        fbaDevanningDetail = new FbaDevanningDetail();
                        addDevanningDetail(fbaBoxDetai, fbaDevanningDetail, fbaDevanning, userInfo, apiResponse,0);
                        if (apiResponse.getCode() == 400) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                    }
                }

                params2 = new HashMap<String, Object>();
                params2.put("codeShipment", fbaBox1.getCodeShipment());
                fbaBoxList = fbaBoxMapper.findFbaBox(params2);
                if (fbaBoxList.size() == 0) {
                    fbaShipment = new FbaShipment();
                    fbaShipment.setCode(fbaBox1.getCodeShipment());
                    fbaShipment.setDeleted(true);
                    //删除货件
                    fbaShipmentMapper.updateByCode(fbaShipment);

                    fbaPlanOrder = new FbaPlanOrder();
                    fbaPlanOrder.setCode(fbaBox1.getCodePlan());
                    fbaPlanOrder.setDeleted(true);
                    //删除头程计划单状态
                    fbaPlanOrderMapper.updateByCode(fbaPlanOrder);
                }
            }else {
                //新增复建的头程装箱，并且将数据回退到已装箱
                FbaBox fbaBox3 = new FbaBox();
                BeanUtils.copyProperties(fbaBox1,fbaBox3);
                //查询头程货件最新数据
                params2 = new HashMap<String, Object>();
                params2.put("moduleTable", "TP_FBABOX");
                moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params2);    //有事务控制，制单异常不跳过单号
                //新增头程装箱单
                fbaBox3.setGuid(RandomValueUtils.getGUID());
                fbaBox3.setNid(moduleNidAndBid.getNid());
                fbaBox3.setBid(moduleNidAndBid.getBid());
                fbaBox3.setCode(moduleNidAndBid.getBid());
                fbaBox3.setShipmentId("");
                fbaBox3.setDestinationFulfillmentCenterId("");
                fbaBox3.setTrackingCode("");
                fbaBox3.setState("2");//已装箱状态
                fbaBox3.setStateName("已装箱");
                if (fbaBox3.getIsfmb() != null){
                    if (fbaBox1.getIsfmb() == 0){
                        fbaBox3.setStatePrint("2");
                        fbaBox3.setStatePrintName("配货清单和商品标已打印");
                    } else {
                        fbaBox3.setStatePrint("3");
                        fbaBox3.setStatePrintName("配货清单和商品标和透明标已打印");
                    }
                }
                fbaBox3.setStateTrack("0");
                fbaBox3.setStateTrackName("无");
                fbaBox3.setAuditUser(null);
                fbaBox3.setAuditTime(null);
                fbaBox3.setBoxMarkUser(null);
                fbaBox3.setBoxMarkTime(null);
                fbaBox3.setDeliveryUser(null);
                fbaBox3.setDeliveryTime(null);
                if (fbaBox3.getCreationMethod().equals("手动")) {
                    fbaBox3.setWarehouseSurchargePrice(BigDecimal.ZERO);
                    //先减去之前增加的仓库附加费
                    fbaBox3.setPriceTranCalWeightPredict(fbaBox3.getPriceTranCalWeightPredict().subtract(fbaBox3.getWarehouseSurcharge()));
                    fbaBox3.setActualLogisticsFreight(fbaBox3.getActualLogisticsFreight().subtract(fbaBox3.getWarehouseSurcharge()));
                    if (fbaBox3.getLoadDelivery().equals("是")) {
                        fbaBox3.setPriceTranCalWeightPredictPf(fbaBox3.getPriceTranCalWeightPredictPf().subtract(fbaBox3.getWarehouseSurchargePf()));
                        fbaBox3.setActualLogisticsFreightPf(fbaBox3.getActualLogisticsFreightPf().subtract(fbaBox3.getWarehouseSurchargePf()));
                        fbaBox3.setWarehouseSurchargePf(BigDecimal.ZERO);
                    }
                    fbaBox3.setWarehouseSurcharge(BigDecimal.ZERO);
                }
                if (fbaBox3.getvZdbz() != null){
                    fbaBox3.setvZdbz(fbaBox3.getvZdbz() + ","+params.get("remark").toString());
                }else {
                    fbaBox3.setvZdbz(params.get("remark").toString());
                }
                fbaBoxMapper.insertFbaBox(fbaBox3);

                //直接拆箱到完成单
                fbaDevanning = new FbaDevanning();
                addDevanning(fbaBox3, params, fbaDevanning, userInfo, apiResponse, fbaShipment1,1);
                if (apiResponse.getCode() == 400) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                if (fbaBoxDetailList.size() != 0) {
                    fbaBoxDetailListNew = JSON.parseArray(fbaBoxDetailList.get(0).getProductInfo(), FbaBoxDetail.class);
                    for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailListNew) {
                        //新增拆箱详情
                        fbaDevanningDetail = new FbaDevanningDetail();
                        addDevanningDetail(fbaBoxDetai, fbaDevanningDetail, fbaDevanning, userInfo, apiResponse,1);
                        if (apiResponse.getCode() == 400) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return apiResponse;
                        }
                    }
                    for (FbaBoxDetail fbaBoxDetai : fbaBoxDetailList) {
                        //新增装箱详情
                        fbaBoxDetaiNew = new FbaBoxDetail();
                        BeanUtils.copyProperties(fbaBoxDetai,fbaBoxDetaiNew);
                        fbaBoxDetaiNew.setGuid(RandomValueUtils.getGUID());
                        fbaBoxDetaiNew.setCodeBox(fbaBox3.getCode());
                        fbaBoxDetailMapper.insertFbaBoxDetail(fbaBoxDetaiNew);
                    }
                }

            }
            fbaBox1.setDeleted(true);
            //删除装箱单
            fbaBoxMapper.updateByGuid(fbaBox1);

            if (fbaBox1.getIsDeliver() != 1) {
//                查询物流部账号
                sysAccountBandDept = sysAccountBandDeptMapper.findByAccountId("WLB");
                if (sysAccountBandDept == null) {
                    apiResponse.setMsg("物流部门绑定账户未启用或不存在,请核实后再操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

                // 物流公司增加物流费用
                logisticsAccount = accountCountForCompanyMapper.queryFirstByVGsBm(sysAccountBandDept.getvGsBm());
                if (logisticsAccount == null) {
                    apiResponse.setMsg("物流公司实时资金不存在,请核实后再操作!");
                    apiResponse.setCode(400);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return apiResponse;
                }

//                    资金流水(物流部 - 运营公司 头程物流费)
                addAccountDetailedForCompany(operationAccount, logisticsAccount, userInfo, -priceTranPredict1,
                        "(回退)头程物流费，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + ",头程拆箱单:" +fbaDevanning.getCodeDevanning() + "," + fbaBox1.getShipmentId() + "," + fbaBox1.getNameLogsticsWay(),
                        "物流服务→头程运费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                );
                //物流部减少头程物流费
                logisticsAccount.setfJe(logisticsAccount.getfJe() - priceTranPredict1);
                accountCountForCompanyMapper.updateAccountCountForCompany(logisticsAccount);

                //资金流水(运营公司 - 物流部 头程物流费)
                addAccountDetailedForCompany(logisticsAccount, operationAccount, userInfo, priceTranPredict1,
                        "(回退)头程物流费，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + ",头程拆箱单:" +fbaDevanning.getCodeDevanning() + "," + fbaBox1.getShipmentId() + "," + fbaBox1.getNameLogsticsWay(),
                        "物流服务→头程运费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                );
                //运营公司增加头程物流费
                operationAccount.setfJe(operationAccount.getfJe() + priceTranPredict1);

                //资金流水(仓储部 - 运营公司 纸箱包装费)
                addAccountDetailedForCompany(operationAccount, warehousingAccount, userInfo, -boxProject,
                        "(回退)纸箱费，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + ",头程拆箱单:" +fbaDevanning.getCodeDevanning() + ",纸箱个数" + fbaBox1.getNumBox(),
                        "仓储服务→纸箱费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                );
                //仓储部减少纸箱包装费
                warehousingAccount.setfJe(warehousingAccount.getfJe() - boxProject);

                //资金流水(运营公司 - 仓储部 纸箱包装费)
                addAccountDetailedForCompany(warehousingAccount, operationAccount, userInfo, boxProject,
                        "(回退)纸箱费，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + ",头程拆箱单:" +fbaDevanning.getCodeDevanning() + ",纸箱个数" + fbaBox1.getNumBox(),
                        "仓储服务→纸箱费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                );
                //运营公司增加纸箱包装费
                operationAccount.setfJe(operationAccount.getfJe() + boxProject);

                if (stringBuffer.length() != 0) {
                    stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                }
                if (transparencyProject != 0.0) {
                    //资金流水(仓储部-运营公司 透明计划贴标费用)
                    addAccountDetailedForCompany(operationAccount, warehousingAccount, userInfo, -transparencyProject,
                            "(回退)透明计划贴标费用，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + ",头程拆箱单:" +fbaDevanning.getCodeDevanning() + "," + stringBuffer,
                            "仓储服务→透明计划贴标费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                    );
                    //仓储部减少 透明计划贴标费用
                    warehousingAccount.setfJe(warehousingAccount.getfJe() - transparencyProject);

                    //资金流水(运营公司-仓储部 透明计划贴标费用)
                    addAccountDetailedForCompany(warehousingAccount, operationAccount, userInfo, transparencyProject,
                            "(回退)透明计划贴标费用，头程计划单:" + fbaBox1.getCodePlan() + ",头程装箱单:" +fbaBox1.getCode() + ",头程拆箱单:" +fbaDevanning.getCodeDevanning() +"," + stringBuffer,
                            "仓储服务→透明计划贴标费", "装箱单", 1, fbaBox1.getNid(), fbaBox1.getCode(), fbaBox1.getGuid(), fbaBox1.getCreateTime(), accountList
                    );
                    //更新仓储部
                    accountCountForCompanyMapper.updateAccountCountForCompany(warehousingAccount);

                    //更新运营公司
                    accountCountForCompanyMapper.updateAccountCountForCompany(operationAccount);
                }


            }

            try {
                businessMapper.insertBatchNew(accountList);
            }catch (Exception e){
                apiResponse.setMsg("新增账户流水单失败!");
                apiResponse.setCode(400);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return apiResponse;
            }



        } catch (Exception e) {
            apiResponse.setCode(500);
            apiResponse.setMsg("完成单拆箱失败!");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return apiResponse;
        }
        apiResponse.setCode(0);
        apiResponse.setMsg("完成单拆箱成功!");
        return apiResponse;
    }

}
